Is it possible to use RedirectToAction () inside a custom class of AuthorizeAttribute?

Using ASP.Net MVC 2, is it possible to use the RedirectToAction () Controller method inside a class based on the AuthorizeAttribute class?

 public class CustomAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase context) { // Custom authentication goes here return false; } public override void OnAuthorization(AuthorizationContext context) { base.OnAuthorization(context); // This would be my ideal result context.Result = RedirectToAction("Action", "Controller"); } } 

I am looking for a way to redirect the user to a specific controller / action when they do not authenticate and do not return them to the login page. Is it possible to have a redirected URL for this controller / action and then use RedirectResult () ? I try to avoid the temptation to just copy the url.

+49
asp.net-mvc
Mar 18 '10 at 18:58
source share
3 answers

You can / should override HandleUnauthorizedRequest instead of OnAuthorization . The default implementation is used here:

  protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. filterContext.Result = new HttpUnauthorizedResult(); } 

You cannot use Controller.RedirectToAction , but you can return a new RedirectToRouteResult .

So you can do:

  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs. filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "action", "ActionName" }, { "controller", "ControllerName" } }); } 
+92
Mar 18 '10 at 19:45
source share

You can do something like this:

 var routeValues = new RouteValueDictionary(); routeValues["controller"] = "ControllerName"; routeValues["action"] = "ActionName"; //Other route values if needed. context.Result = new RedirectToRouteResult(routeValues); 

This is the way the framework does when you call "RedirectToAction ()" in your controller.

+11
Mar 18 '10 at 19:44
source share

If anyone else is interested in this question. This can be solved in a simpler way (at least using MVC 3, I don't know about MVC 2):

Just create a small private controller in your custom AuthorizeAttribute attribute:

  private class RedirectController : Controller { public ActionResult RedirectWhereever() { return RedirectToAction("Action", "Controller"); } } 

This can be easily used in the HandleUnauthorizedRequest method (see Craigs answer):

 filterContext.Result = (new RedirectController()).RedirectWhereever(); 
+2
Jul 22 '11 at 11:19
source share



All Articles