Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 404 error message in Web API responses

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

like image 624
Raghav Avatar asked Jan 21 '18 17:01

Raghav


1 Answers

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."

like image 60
Raghav Avatar answered Oct 06 '22 00:10

Raghav