具有自定义重定向的AuthorizeAttribute

时间:2010-10-15 14:57:36

标签: asp.net-mvc redirect authorization

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

我试图添加

<customErrors mode="On" > 
       <error statusCode="401" redirect="/Errors/NotAuthorized/" /> 
</customErrors> 

但它不起作用。

1 个答案:

答案 0 :(得分: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");
            }
        }
    }

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

相关问题