I\'m using an AuthorizeAttribute on various controllers which may need to return 403 or 429 (too many requests) based on certain attributes of the request itself. I implemented
As you have discovered, throwing exceptions is expensive. The trick in this case is to override the response in the attribute. As MVC and WebAPI are different (at least prior to MVC6) there are two distinct methods.
Setting the AuthorizationContext.Result allows you to effectively override what action is being performed. Setting this value will prevent the action it is attached to from running at all:
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(Throw403)
{
filterContext.Result = new HttpStatusCodeResult(403);
}
}
Very similar but you must instead set the HttpActionContext.Response property. One handy feature of this, is that you get a nice enum
for the HTTP status code:
public override void OnAuthorization(HttpActionContext actionContext)
{
if(Throw403)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}