Allow multiple roles to access controller action

前端 未结 9 1243
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 15:19

Right now I decorate a method like this to allow \"members\" to access my controller action

[Authorize(Roles=\"members\")]

How do I

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 15:34

    If you find yourself applying those 2 roles often you can wrap them in their own Authorize. This is really an extension of the accepted answer.

    using System.Web.Mvc;
    
    public class AuthorizeAdminOrMember : AuthorizeAttribute
    {
        public AuthorizeAdminOrMember()
        {
            Roles = "members, admin";
        }
    }
    

    And then apply your new authorize to the Action. I think this looks cleaner and reads easily.

    public class MyController : Controller
    {
        [AuthorizeAdminOrMember]
        public ActionResult MyAction()
        {
            return null;
        }
    }
    

提交回复
热议问题