是否有可能使用RedirectToAction()的自定义AuthorizeAttribute类中? [英] Is it possible to use RedirectToAction() inside a custom AuthorizeAttribute class?

查看:118
本文介绍了是否有可能使用RedirectToAction()的自定义AuthorizeAttribute类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ASP.Net MVC 2,有没有什么办法来使用RedirectToAction() 类内部类的方法,它是基于在 AuthorizeAttribute 类?

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

我正在寻找一种方式来重新将用户引导到一个特定的控制器/动作时,他们无法通过验证,而不是将其返回到登录页面。是否有可能让该控制器/动作所产生的重新定向的网址,然后使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.redirectresult.aspx\">RedirectResult()?我试图避免的诱惑,只是硬code中的URL。

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.

推荐答案

您可以/应该重写 HandleUnauthorizedRequest 而不是 OnAuthorization 。这里的默认实现:

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

您不能使用 Controller.RedirectToAction ,但你的可以的返回一个新的 RedirectToRouteResult

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

所以,你可以这样做:

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
        filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary 
                                   {
                                       { "action", "ActionName" },
                                       { "controller", "ControllerName" }
                                   });
    }

这篇关于是否有可能使用RedirectToAction()的自定义AuthorizeAttribute类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆