加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 具有自定义重定向的AuthorizeAttribute

发布时间:2020-12-16 06:54:06 所属栏目:asp.Net 来源:网络整理
导读:我想使用标准的AuthorizeAttribute(即不继承它),但使用自定义重定向.那可能吗?我应该在哪里检查401并重定向? 我试过补充一下 customErrors mode="On" error statusCode="401" redirect="/Errors/NotAuthorized/" / /customErrors 但它不起作用. 解决方法
我想使用标准的AuthorizeAttribute(即不继承它),但使用自定义重定向.那可能吗?我应该在哪里检查401并重定向?

我试过补充一下

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

但它不起作用.

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读