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

如何从ASP.NET MVC中的某些操作的Authorize Attribute获取角色数

发布时间:2020-12-16 07:00:07 所属栏目:asp.Net 来源:网络整理
导读:假设我有以下控制器和具有授权属性的操作: public class IndexController : Controller { // // GET: /Index/ [Authorize(Roles="Registered")] public ActionResult Index() { return View(); } } 我搜遍了整个互联网,但没有找到这个简单问题的答案:如何
假设我有以下控制器和具有授权属性的操作:

public class IndexController : Controller
    {
        //
        // GET: /Index/

        [Authorize(Roles="Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }

我搜遍了整个互联网,但没有找到这个简单问题的答案:如何将角色注释到特定的动作/控制器?在这种情况下:索引操作有:string [] = {“Registered”}

解决方法

最后我找到了解决方案!比我想象的更容易! ahahha我需要从AuthorizeAttribute扩展一个类并在动作中使用它.我需要的信息是继承类的属性“角色”:

public class CustomAuthorizationAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        var roles = this.Roles;

        base.OnAuthorization(filterContext);
    }

}

在索引控制器上:

public class IndexController : Controller
    {
        //
        // GET: /Index/

        [CustomAuthorizationAttribute(Roles = "Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }

(编辑:李大同)

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

    推荐文章
      热点阅读