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