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

后端 未结 3 1925
梦毁少年i
梦毁少年i 2020-12-02 16:47

Using ASP.Net MVC 2, is there any way to use the RedirectToAction() method of the Controller class inside a class that is based on the AuthorizeAttribute class?

相关标签:
3条回答
  • 2020-12-02 17:05

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

    Just create a small private controller in your custom AuthorizeAttribute:

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

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

    filterContext.Result = (new RedirectController()).RedirectWhereever();
    
    0 讨论(0)
  • 2020-12-02 17:22

    You can/should override HandleUnauthorizedRequest instead of OnAuthorization. Here's the default implementation:

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

    You can't 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" }
                                       });
        }
    
    0 讨论(0)
  • 2020-12-02 17:24

    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 it when you call "RedirectToAction()" in your controller.

    0 讨论(0)
提交回复
热议问题