1

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.

4
  • You could return HttpResponseMessage instead? Commented Nov 28, 2014 at 10:34
  • I am returning HttpResponseMessage from my Error Controller. Problem is how to catch "405" error. Commented Nov 28, 2014 at 10:49
  • have you looked here asp.net/web-api/overview/testing-and-debugging/… Commented Nov 28, 2014 at 11:01
  • Yes I did. Good detail on 405 errors. But still, there is nothing about how to show our own custom errors instead of 405 errors Commented Nov 28, 2014 at 12:38

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.