ASP.NET MVC: Can I say [Authorize Roles=“Administrators”] on the Controller class, but have one public action?

前端 未结 3 1728
天命终不由人
天命终不由人 2021-01-13 04:24

I started off using the default project\'s AccountController, but I\'ve extended/changed it beyond recognition. However, in common with the original I have a

3条回答
  •  长情又很酷
    2021-01-13 05:04

    After way too much time, I came up with a solution.

    public class OverridableAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var action = filterContext.ActionDescriptor;
            if(action.IsDefined(typeof(IgnoreAuthorization), true)) return;
    
            var controller = action.ControllerDescriptor;
            if(controller.IsDefined(typeof(IgnoreAuthorization), true)) return;
    
            base.OnAuthorization(filterContext);
        }
    }
    

    Which can be paired with IgnoreAuthorization on an Action

    public class IgnoreAuthorization : Attribute
    {
    }
    

提交回复
热议问题