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.