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

£可爱£侵袭症+ 提交于 2019-12-01 05:51:32
David Glenn

To override an controller Attribute at the Action level you have to create a custom Attribute and then set the Order property of your custom attribute to a higher value than the controller AuthorizeAttribute. I believe both attributes are then still executed unless your custom attribute generates a result with immediate effect such as redirecting.

See Overriding controller AuthorizeAttribute for just one action for more information.

So I believe in your case you will just have to add the AuthorizeAttribute on the Actions and not at the controller level. You could however create a unit test to ensure that all Actions (apart from LogOn) have an AuthorizeAttribute

You can use AuthorizeAttribute on your class

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

For relaxing you can implement for example a custom action filter attribute like this (I didn' test if it works).

public class GetRidOfAutorizationAttribute : AuthorizeAttribute 
{
public override void OnAuthorization(AuthorizationContext filterContext)
{

// you can for example do nothing
filterContext.Result = new EmptyResult(); 

}
}

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
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!