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

后端 未结 3 1938
梦毁少年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: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" }
                                       });
        }
    

提交回复
热议问题