0

I am trying to handle 405 (Method not Allowed) errors generated from WebApi.

E.g.: Basically this error will be handled whenever someone calls my Api with a Post request instead of a Get one.

I'd like to do this programatically (i.e. no IIS configuration), right now there are no documentation of handling this kind of error and the IExceptionHandler is not triggered when this exception happens.

Any ideas ?

Ayman
  • 1,387
  • 4
  • 20
  • 35

1 Answers1

1

Partial response: By looking at the HTTP Message lifecycle from here, there is a possibility to add a Message Handler early in the pipeline, before HttpRoutingDispatcher.

So, create a handler class:

public class NotAllowedMessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            switch (response.StatusCode)
            {
                case HttpStatusCode.MethodNotAllowed:
                {
                    return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)
                    {
                        Content = new StringContent("Custom Error Message")
                    };
                }
            }
        }

        return response;
    }
}

In your WebApiConfig, in Register method add the following line:

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

You can check the status code of the response and generate a custom error message based on it.

Ayman
  • 1,387
  • 4
  • 20
  • 35