Search code examples
asp.net-mvcrestasp.net-web-apicustom-errorshttpexception

Handling HTTP "405" error in web api using application_error() event


I am using Application_Error() event to get all HTTP exceptions in web API. This event is returning all HTTP codes e.g."404","500" and using "Server.TransferRequest()" to transfer request to my "Error controller" for showing custom errors. But Application_Error() does not fire in case of HTTP Error "405"("The requested resource does not support HTTP method 'GET/POST/PUT/DELETE'). I want to show my own custom error in case of "405". One way to achieve this can be like this: Exposing (GET,POST,PUT,DELETE) methods for all controllers in API and return my own custom errors from these methods. But it will not be a good way to achieve the purpose. Can anybody guide me about a clean way to do this? Any help will be highly appreciated.


Solution

  • I know it's a bit late, but what you want is possible with MessageHandlers:
    http://www.asp.net/web-api/overview/advanced/http-message-handlers

    You have to implement a DelegatingHandler

    public class MethodNotAllowedHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
            CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            if (response.StatusCode == System.Net.HttpStatusCode.MethodNotAllowed)
            {
                //do your handling here
                //maybe return a new HttpResponseMessage
            }
            return response;
        }
    }
    

    Then you add it to your HttpConfiguration

    config.MessageHandlers.Add(new MethodNotAllowedHandler());