I need to modify the message which comes when the Web API throws 404 error:
Right now if any api doesn't exists let's say on accessing https://mywebsite/api/foo/?%22%26gt;%26lt;script%26gt;_q_q=)(%26lt;/script%26gt;
I get the following response:
{ "Message": "No HTTP resource was found that matches the request URI 'https://mywebsite/api/foo/?\"><script>_q_q=)(</script>'.", "MessageDetail": "No action was found on the controller 'MyController' that matches the request." }
I want to modify this message.
In order to do that I tried this..
I added a custom attribute over my controller:
[NoActionFoundFilterAttribute]
public class MyController
The code of filter is:
public class NoActionFoundFilterAttribute: ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
// My code
}
}
And in Web API Config I have already added the filter:
config.Filters.Add(new NoActionFoundFilterAttribute());
Even after doing all the above steps the OnException method "NoActionFoundFilterAttribute" file is not being hit when invalid action is being called.
Can you share what I am missing in order to modify the custom 404 error message
I was able to find the solution.
Here is what I did:
I added the following line to hook into Web API response pipeline for the messages returned by Web API:
config.MessageHandlers.Add(new WebApiCustomMessageHandler());
and then I implemented the WebApiCustomMessageHandler like this:
public class WebApiCustomMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
request.Properties.Remove(HttpPropertyKeys.NoRouteMatched);
var errorResponse = request.CreateResponse(response.StatusCode, "Content not found.");
return errorResponse;
}
return response;
}
}
After implementing the above solution I was able to modify the ContentNotFound responses from WebAPI. The response finally came like this:
"Content not found."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With