Can you return an HTTP response from an AuthorizeAttribute without throwing an exception?

后端 未结 2 1253
逝去的感伤
逝去的感伤 2021-02-19 05:14

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

相关标签:
2条回答
  • 2021-02-19 06:07

    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.

    MVC

    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);
        }
    }
    

    WebAPI

    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);
        }
    }
    
    0 讨论(0)
  • 2021-02-19 06:13

    How about custom message handlers where you could respond back even before hitting the controller? This happens early in the pipeline.

    Edit - pasting relevant info from website

    A delegating handler can also skip the inner handler and directly create the response:

    public class MessageHandler2    :DelegatingHandler
    {
     protected override    Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Create the response.
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("Hello!")
        };
    
        // Note: TaskCompletionSource creates a task that does not contain a delegate.
        var tsc = new TaskCompletionSource<HttpResponseMessage>();
        tsc.SetResult(response);   // Also sets the task state to "RanToCompletion"
        return tsc.Task;
       }
    }
    

    And this is how you register the handler

      public static class WebApiConfig
        {
      public static void        Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new MessageHandler1());
        config.MessageHandlers.Add(new MessageHandler2());
    
        // Other code not shown...
    }
    }
    

    Ref here: http://www.asp.net/web-api/overview/advanced/http-message-handlers

    sorry for the bad formatting, this is the best I could do via mobile

    0 讨论(0)
提交回复
热议问题