Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

asp.net mvc - Is it possible to use RedirectToAction() inside a custom AuthorizeAttribute class?

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?

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'm looking for a way to re-direct the user to a specific controller / action when they fail the authentication instead of returning them to the login page. Is it possible to have the re-direct URL generated for that controller / action and then use RedirectResult()? I'm trying to avoid the temptation to just hard-code the URL.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" }
                                   });
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...