I have a CustomAuthorizeAttribute default CustomAuthorizeAttribute defined in my Web Api project.
config.Filters.Add(new CustomAuthorizeAttribute());
However, I have a special controller where I would like to use SpecialAuthorizeAttribute .
[SpecialAuthorize] public class MySpecialController : ApiController
In Asp.Net vNext, we have a new attribute to override the default filters, but how can I get it to work in Web Api 2?
Change 1:
One possible (but not ideal) solution is to have CustomAuthorizeAttribute check to see if there is another AuthorizeAttribute attribute in the Controller or Action area. In my case, I only have SpecialAuthorizeAttribute, so:
public class CustomAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any() || actionContext.ActionDescriptor.GetCustomAttributes<SpecialAuthorizeAttribute>().Any()) { return; } base.OnAuthorization(actionContext); } public override System.Threading.Tasks.Task OnAuthorizationAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { return base.OnAuthorizationAsync(actionContext, cancellationToken); } }
source share