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 ?

2
  • The webserver is an IIS on Windows Server? Commented Dec 18, 2017 at 10:20
  • Yes, but I don't have control over the server or IIS, so it would be preferable if there is a way to handle it programatically. Commented Dec 18, 2017 at 10:22

1 Answer 1

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.

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.