具有自定义重定向的AuthorizeAttribute

jga*_*fin 4 asp.net-mvc redirect authorization

我想使用标准的AuthorizeAttribute(即不继承它),但使用自定义重定向.那可能吗?我应该在哪里检查401并重定向?

我试过补充一下

<customErrors mode="On" > 
       <error statusCode="401" redirect="/Errors/NotAuthorized/" /> 
</customErrors> 
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

jga*_*fin 7

在我的ApplicationController中做了这个:

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var attributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true);
        if (attributes.Length == 0)
            attributes = GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
        if (attributes.Length == 0)
            return;

        foreach (AuthorizeAttribute item in attributes)
        {
            if (!Thread.CurrentPrincipal.IsInRole(item.Roles))
            {
                filterContext.Result = new RedirectResult("/Errors/Unauthorized");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我会奖励任何有更好解决方案的人.