I need to redirect to an external url (let's say "www.google.com") from OnActionExecuting method. Right now I'm using something like this:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var redirectUrl = "www.google.com";
try
{
var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();
if (isAjaxRequest)
{
filterContext.HttpContext.Response.StatusCode = SessionController.CustomHttpRedirect;
filterContext.HttpContext.Response.StatusDescription = redirectUrl;
filterContext.Result = new JsonResult
{
Data = new { Redirect = redirectUrl },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
filterContext.Result = new RedirectResult(redirectUrl, true);
}
return;
}
else
{
throw new LoggedOutException();
}
}
catch
{
throw new LoggedOutException();
}
}
}
The problem is that it's not redirecting me to "www.google.com" but it's redirecting to "http://localhost:1234/www.google.com" (I try it locally).
There is any way to solve this ?
Thanks
The problem was verry easy to solve:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
var redirectUrl = "http://www.google.com";
try
{
var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();
if (isAjaxRequest)
{
filterContext.HttpContext.Response.StatusCode = SessionController.CustomHttpRedirect;
filterContext.HttpContext.Response.StatusDescription = redirectUrl;
filterContext.Result = new JsonResult
{
Data = new { Redirect = redirectUrl },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
filterContext.Result = new RedirectResult(redirectUrl, true);
}
return;
}
else
{
throw new LoggedOutException();
}
}
catch
{
throw new LoggedOutException();
}
}
}
All I had to do was that when I assigned the value to "redirectUrl", I had tu put http before wwww. This mus be put if you use a SSL conenction and you're trying to redirect from mvc to another domain.
Instead of using:
filterContext.Result = new RedirectResult("www.google.com", true);
Try the following:
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "External" , ReturnURL = "www.google.com"}));
and in your (Home) controller create an action called (External) and from there redirect to your external url:
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult External(string ReturnURL){
return Redirect(ReturnURL);
}
}
You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript. see this answer
Related
I have developed a module which authorizes the roles from the database dynamically. Now, what i want is,when a user comes and browses different actionmethod without logging in, I am able to redirect the user to the login page. As soon as the user logs in, he should be redirected to the actionmethod/view which he was trying to access without login. The following is the code which i am using to extract the URL browsed without logging in. I also have a key defined in my web.config as serverURL which gives me initial url like localhost. How to i make the below returnurl remembered and redirect the user to the desired actionmethod/view after logging in.
returnUrl = HttpContext.Current.Request.RawUrl;
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string Feature { get; set; }
public string returnUrl { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//var isAuthorized = base.AuthorizeCore(httpContext);
//if (!isAuthorized)
//{
// return false;
//}
if (httpContext != null && httpContext.Session != null && httpContext.Session["Role"] != null)
{
string userRoles = UserBL.ValidateUsersRoleFeature(httpContext.Session["Role"].ToString(), Feature);
if (!string.IsNullOrEmpty(userRoles))
{
if (userRoles.IndexOf(httpContext.Session["Role"].ToString()) >= 0)
{
return true;
}
}
return false;
}
else
return false;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
if (session.IsNewSession || session["Email"] == null)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// For AJAX requests, return result as a simple string,
// and inform calling JavaScript code that a user should be redirected.
JsonResult result = new JsonResult();
result.ContentType = "text/html";
result.Data = "SessionTimeout";
filterContext.Result = result;
//$.ajax({
// type: "POST",
// url: "controller/action",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// data: JSON.stringify(data),
// async: true,
// complete: function (xhr, status) {
// if (xhr.responseJSON == CONST_SESSIONTIMEOUT) {
// RedirectToLogin(true);
// return false;
// }
// if (status == 'error' || !xhr.responseText) {
// alert(xhr.statusText);
// }
// }
// });
//}
}
else
{
// For round-trip requests,
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "Controller", "User" }, { "Action", "Login" } });
returnUrl = HttpContext.Current.Request.RawUrl;
}
}
else
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Base",
action = "PageNotAccessible"
})
);
}
}
In attribute return the url on which user was in routes:
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "Controller", "User" },
{ "Action", "Login" },
{"returnUrl",HttpContext.Current.Request.RawUrl}
});
and in your action:
[AllowAnonymous]
public virtual ActionResult Login()
{
ViewBag.returnUrl = Request.QueryString["returnUrl"];
return View();
}
In View:
#using(Html.BeginForm("Login","User",new{returnUrl = ViewBag.returnUrl},FormMethod.Post))
{
<input type="submit" value="Login" />
}
and in Post Action:
[AllowAnonymous]
[HttpPost]
public virtual ActionResult Login(User model, string returnUrl)
{
if(ModelState.IsValid)
{
// check if login successful redirect to url from where user came
if(LoginSucessful)
return Redirect(returnUrl); // will be redirected to url from where user came to login
return View();
}
in your html page, create a hidden tag:
<div id="HiddenURL" class="hidden"></div>
the moment the user access a certain page, use Javascript to bind the url the user came from in a hidden value in you web page:
$(document).ready(function ()
{
$('#HiddenURL').text(window.location.href.toLowerCase());
...
}
In your asp.net page assign to action, the url taken from div text:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Base",
action = HiddenURL.Value
})
);
}
I have a need to override authorize attribute.
Basically if its an ajax request and the user is not logged in or is not in specified roles then i want to return a JSON. The JSON will tell the caller the reason as not logged in or not in role and needs to return the redirect to url. In case of not signed it, it also needs to give back ReturnUrl.
If its not an ajax request then i want the default processing by Authorize attribute to kick in.
We are using forms authentication and the sign in url and error pages are specified in the web.config file.
Following is my take at it but i am not getting the following right
missing roles processing in case of an ajax request
in case of not an ajax request (else block), i am redirecting the user to the sign in page. i want the default autorize attribute to kickin in this case
I just need the push in the right direction... tutorial or a blog pointer is all i need to learn and accomplish this....
public class AuthorizePartnerProgramsAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpContext httpContext = HttpContext.Current;
var url = new UrlHelper(filterContext.RequestContext);
var request = filterContext.HttpContext.Request;
if (request.IsAuthenticated == false)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
if (request.Url != null)
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!", returnUrl = request.UrlReferrer.AbsolutePath.ToString() } });
else
filterContext.Result = CommonUtilities.AddJsonUtf8Encoding(new JsonResult { Data = new { error = true, singinerror = true, message = "Sign in required!" } });
}
else
{
if (request.UrlReferrer != null)
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = filterContext.RequestContext.HttpContext.Request.UrlReferrer.AbsolutePath.ToString() }));
}
else
{
filterContext.Result = new RedirectResult(url.Action("Index", "SignIn", new { Area = "Account"}));
}
}
}
}
}
Here is my second stab at it. I think i am now more confused than before and need help setting it up properly
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var request = filterContext.RequestContext.HttpContext.Request;
if (request.IsAjaxRequest())
{
var url = new UrlHelper(filterContext.RequestContext);
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
if (!request.IsAuthenticated)
{
//not authenticated
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, singinerror = true, message = "Sign in required!", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Request.IsAjaxRequest())
{
//Use [AuthorizeCustom(Roles="MyRole1,MyRole2")]
//or [AuthorizeCustom]
//roles may not have been applied here
//checking authentication will be done by the HandleUnauthorizedRequest?????
//if no roles are specified then it is true = so give access to the resource
//user may have multiple roles or single role assigned, check and if not in role then return json back.
//....
}
else
{
return base.AuthorizeCore(httpContext);
}
}
}
This helped me setting up mine
http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html
use
[AuthorizeCustom(Roles = RoleNames.Admin)]
Here is the full working attribute for me without any cleanup.
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
#region CONSTANTS
public const string SectionStemFuture = "StemFuture";
#endregion
#region PROPERTIES
private string Section { get; set; }
#endregion
#region Constructor
public AuthorizeCustomAttribute()
{
Section = String.Empty;
}
public AuthorizeCustomAttribute(string section)
{
Section = section;
}
#endregion
#region Overrides
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
var url = new UrlHelper(filterContext.RequestContext);
/*
var urlReferer = request.UrlReferrer != null
? request.UrlReferrer.ToString()
: String.Empty;
*/
var urlReferer = request.Url.PathAndQuery;
var signInUrl = url.Action("Index", "SignIn", new { Area = "Account", ReturnUrl = urlReferer });
var accessDeniedUrl = url.Action("PageAccessDenied", "Error", new { Area = "" });
//overwrite the default sign in URL according to the section
if (!String.IsNullOrWhiteSpace(Section))
{
switch (Section)
{
case SectionStemFuture:
signInUrl = url.Action("Index", "StemFutureHome", new { Area = "StemFuture", ReturnUrl = urlReferer });
break;
}
}
if (!request.IsAuthenticated)
{
//not authenticated
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new {error = true, signinerror = true, message = "Sign in required", url = signInUrl},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//this is not an ajax request
if (!String.IsNullOrWhiteSpace(Section))
{
filterContext.Result = new RedirectResult(signInUrl);
}
else
{
//let the base authorization take care of it
base.OnAuthorization(filterContext);
}
}
}
else if (!String.IsNullOrWhiteSpace(base.Roles))
{
var isRoleError = true;
var rolesAllowed = base.Roles.Split(',');
//authenticated and we have some roles to check against
var user = filterContext.HttpContext.User;
if (user != null && rolesAllowed.Any())
{
foreach (var role in rolesAllowed)
{
if (user.IsInRole(role))
{
isRoleError = false;
}
}
}
if (isRoleError)
{
if (request.IsAjaxRequest())
{
filterContext.Result =
CommonUtilities.AddJsonUtf8Encoding(new JsonResult
{
Data =
new
{
error = true,
signinerror = true,
message = "Access denied",
url = accessDeniedUrl
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
});
}
else
{
//here we will need to pass to the access denied
filterContext.Result = new RedirectResult(accessDeniedUrl);
}
}
}
}
#endregion
}
I am using asp.net mvc4 and facing problem while creating custom authorize attribute.
The problem i am facing is that it keep coming on this "OnAuthorization" function and not redirecting to appropriate area.
This is what i am trying to do:-
This is my custom authorize attribute:-
public class BusinessAuthorizeFilter:IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// if action or its controller has AllowAnonymousAttribute do nothing
if filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute),
true) ||filterContext.ActionDescriptor.ControllerDescriptor.IsDefined
(typeof(AllowAnonymousAttribute), true))
return;
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
RedirectToArea("Login", "Account", "");
return;
}
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (filterContext.HttpContext.User.IsInRole("Owner"))
route = new RouteValueDictionary{ {"action", "Index"},
{"controller", "HomeAdmin"},
{"area", "Admin"}
}
else if (filterContext.HttpContext.User.IsInRole("Agent"))
route = new RouteValueDictionary{ {"action", "Index"},
{"controller", "HomeAgent"},
{"area", "Agent"}
}
else
route = new RouteValueDictionary{ {"action", "Index"},
{"controller", "HomeSalesRep"},
{"area", "SalesRep"}
}
}
filterContext.Result = new RedirectToRouteResult(route);
}
Please let me know how to make it work.
Thanks in advance.
i got my code working with below thing(although have some question which i'll post as other question):-
public override void OnAuthorization(AuthorizationContext filterContext)
{
// if action or its controller has AllowAnonymousAttribute do nothing
if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
return;
bool isAuthorize = base.AuthorizeCore(filterContext.HttpContext);
if (!isAuthorize==true)
{
var result = new ViewResult();
result.ViewName = "../Error/Unauthorized";
filterContext.Result = result;
return;
}
}
Actually instead of redirecting user here, i simply check whether he's an authorized user or not.
I search for a generic way to display thrown exceptions without redirecting to an error page but displaying it in the same view. I tried these below:
1) I firstly tried to handle them by adding a custom filter in global.asax and overriding public override void OnException(ExceptionContext filterContext) in my Attribute class but in that way, I couldn't fill filterContext.Result in the way I want since the old model of the view is not reachable so I could only redirect to an error page but that's not what I want.
2) Then I tried to catch the exceptions on my BaseController(All of my controllers inherits from it). I again override public override void OnException(ExceptionContext filterContext) in my controller and put exception details etc. in ViewBag and redirected the page to the same view by filterContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Path ); but ViewBag contents are lost in the redirected page so I can't think any other way?
How can I achieve that? Code Sample that I wrote in my BaseController is below:
protected override void OnException(ExceptionContext filterContext) {
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
//filterContext.Result = new ViewResult
//{
// ViewName = actionName,
// ViewData = new ViewDataDictionary<??>(??),
// TempData = filterContext.Controller.TempData,
//};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
ModelState.AddModelError("Error", filterContext.Exception.Message);
ViewBag.das = "dasd";
filterContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.Path);
}
Maybe you could set a property in your BaseController class to have the name of the view that you want to use, setting that in whatever controller action handles the request. Then in OnException() you could have a method, that redirects to a controller action, that just returns a View that corresponds to the view name? Each controller action would have to set a default view name before it does anything else because only it knows what view it will call if any, and what view it likely was invoked by.
You'd need some sort of BaseController action that returns the new View.
The route(s) may or many not need configuration to have some sort of optional parameter(s) that you could set to be what error information you want to send to your view. For example, in the default route:
routes.MapRoute(RouteNames.Default,
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = "", errorInfo = UrlParameter.Optional}
BaseController:
protected ActionResult ErrorHandler()
{
ViewBag.das = (string)filterContext.RouteData.Values["errorInfo"];
return View(ViewName);
}
protected string ViewName { get; set; }
protected void GoToErrorView(ExceptionContext context, string exceptionData)
{
var actionName = "ErrorHandler";
var newVals = new RouteValueDictionary();
newVals.Add("errorInfo", exceptionData);
this.RedirectToAction(actionName, newVals);
}
In BaseController.OnException():
// ...
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
ModelState.AddModelError("Error", filterContext.Exception.Message);
// anything else you need to do to prepare what you want to display
string exceptionData = SomeSortOfDataYouWantToPassIntoTheView;
this.GoToErrorView(filterContext, exceptionData);
}
In the specific controllers that inherit from BaseController that are returning an ActionResult specifically a ViewResult:
[HttpGet]
public ActionResult Index()
{
ViewName = <set whatever view name you want to here>
// code here, including preparing the Model
// ...
var model = new MyViewModel();
model.SomethingIWantToGiveTheView = someDataThatItNeeds;
// ...
return View(<model name>, model);
}
I found the solution a while ago and add the solution so that it may help the others. I use TempData and _Layout to display errors:
public class ErrorHandlerAttribute : HandleErrorAttribute
{
private ILog _logger;
public ErrorHandlerAttribute()
{
_logger = Log4NetManager.GetLogger("MyLogger");
}
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
// if the request is AJAX return JSON else view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
error = true,
message = filterContext.Exception.Message
}
};
filterContext.HttpContext.Response.StatusCode = 500;
}
// log the error using log4net.
_logger.Error(filterContext.Exception.Message, filterContext.Exception);
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
if (filterContext.Controller.TempData["AppError"] != null)
{
//If there is a loop it will break here.
filterContext.Controller.TempData["AppError"] = filterContext.Exception.Message;
filterContext.HttpContext.Response.Redirect("/");
}
else
{
int httpCode = new HttpException(null, filterContext.Exception).GetHttpCode();
switch (httpCode)
{
case 401:
filterContext.Controller.TempData["AppError"] = "Not Authorized";
filterContext.HttpContext.Response.Redirect("/");
break;
case 404:
filterContext.Controller.TempData["AppError"] = "Not Found";
filterContext.HttpContext.Response.Redirect("/");
break;
default:
filterContext.Controller.TempData["AppError"] = filterContext.Exception.Message;
//Redirect to the same page again(If error occurs again, it will break above)
filterContext.HttpContext.Response.Redirect(filterContext.RequestContext.HttpContext.Request.RawUrl);
break;
}
}
}
}
}
And in Global.asax:
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((MvcApplication)sender).Context;
var ex = Server.GetLastError();
httpContext.ClearError();
httpContext.Response.Clear();
httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
httpContext.Response.TrySkipIisCustomErrors = true;
var routeData = new RouteData();
routeData.Values["controller"] = "ControllerName";
routeData.Values["action"] = "ActionName";
routeData.Values["error"] = "404"; //Handle this url paramater in your action
((IController)new AccountController()).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
I have a controller method that returns a void because it is building an Excel report for the user to download. The Excel 3rd party library we're using is writing to the response itself. The method looks something like this:
[HttpGet]
public void GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
}
catch (Exception ex)
{
// This is wrong, of course, because I'm not returning an ActionResult
Response.RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
There are several security checks in place that throw exceptions if the user doesn't meet certain credentials for fetching the report. I want to redirect to a different page and pass along some information about the exception, but I can't figure out how to do this in MVC3....
Any ideas?
You could use the following code
Response.Redirect(Url.Action("Error", "Report", new { exceptionType = ex.GetType().Name }));
But have you taken a look at the FilePathResult or FileStreamResult ?
Instead of letting the 3rd part library write to the response directly get the content use regular ActionResult and return File(...) for the actual file or RedirectToAction(...) (or RedirectToRoute(...)) on error. If your 3rd party library can only write to Response you may need to use some tricks to capture it's output.
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
var content = excelReport.MakeReport(System.Web.HttpContext.Current.Response);
return File(content, "application/xls", "something.xls");
}
catch (Exception ex)
{
RedirectToRoute("/Report/Error/", new { exceptionType = ex.GetType().Name });
}
}
You can return an EmptyActionResult:
[HttpGet]
public ActionResult GetExcel(int id)
{
try
{
var report = _reportService.GetReport(id);
var table = _reportService.GetReportTable(id);
var excelReport = new ExcelReport(table, report.Name);
excelReport.DownloadReport(System.Web.HttpContext.Current.Response);
return new EmptyResult();
}
catch (Exception ex)
{
return RedirectToAction("Error", "Report", rnew { exceptionType = ex.GetType().Name });
}
}
Not sure if it works, haven't tested it.
Another approach would be using an exception filter:
public class MyExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var routeValues = new RouteValueDictionary()
{
{ "controller", "Error" },
{ "action", "Report" }
};
filterContext.Result = new RedirectToRouteResult(routeValues);
filterContext.ExceptionHandled = true;
// Or I can skip the redirection and render a whole new view
//filterContext.Result = new ViewResult()
//{
// ViewName = "Error"
// //..
//};
}
}