Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API - How to Prevent 404 HTML Response?

How can I change ASP.NET Web API to never return a text/html 404 response? I'd rather it send back XML/JSON with an ExceptionMessage or Message. It doesn't make sense to return HTML from an API, IMO.

Just to clarify, this is for cases when the URL truly is invalid.

Another problem is that I am hosting MVC and Web API in the same project, so I need to respond differently. I am guessing it will depend on whether the URL starts with "api".

like image 605
Travis Parks Avatar asked Jan 22 '14 20:01

Travis Parks


People also ask

How do I handle 404 error in API?

You fix this by opening the listen step in your VSM file, and changing the base path in there, so you don't get a 404 error. You could change that to "/api/" so any api requests are dealt-with, or "/api/retrieveId/" so only retrieveId messages are dealt-with, or "/" so all requests are dealt-with.

What can someone say if your API returns 404?

404 means The server has not found anything matching the Request-URI. If you put in the wrong URI or bad URI that is your problem and the reason you didn't get to a resource whether a HTML page or IMG.

Can you return 404 for a post request?

In short: No. Your API should be "user-friendly" meaning, if there is an error it should return it in a way that the user can figure out what the problem was. Returning 404 is like saying that the service was not found which is not true.


1 Answers

You do not get those HTML data if you simply call throw new HttpResponseException(HttpStatusCode.NotFound); somewhere in your ApiController's methods.

You get this page only when routing mechanism can't fit your request to any of your ApiController's methods. So the HTML message is attached on the application level not in ApiControllers. Here is very good example how you can handle errors in your ASP.NET application Custom error pages on ASP>NET MVC3.

I would even go further and check if the request comes to WebAPI (not to MVC), and if so redirect to IHttpActionResult in ErrorsContoller. How to prepare IHttpActionResult for response you can read here Action Results in Web API 2

like image 82
Sebastian Xawery Wiśniowiecki Avatar answered Sep 22 '22 11:09

Sebastian Xawery Wiśniowiecki