9

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

6
  • What does the returned HTML contain? Are you sure that this error is returned by the Web API? Are those custom 404 messages returned by your Web API endpoints? Or 404 related to endpoints not found? Commented Jan 22, 2014 at 20:52
  • 1
    This is someone trying to request something from my API and they just totally type in the wrong URL. Commented Jan 22, 2014 at 20:55
  • 1
    But this has nothing to do with Web API. Why is your question tagged with it in this case? This is the standard ASP.NET error page. I wrote some example of how you could handle errors using the Application_Error event in Global.asax: stackoverflow.com/a/5229581/29407 Commented Jan 22, 2014 at 20:55
  • 1
    Could you please explain why it doesn't have anything to do with Web API? I understand that normally you use customErrors to change the response. Is this as simple as setting the URL to a desired API end-point? Is there a way to discern whether it is an API call vs. an MVC call? Commented Jan 22, 2014 at 20:59
  • 1
    It doesn't have anything to do with the Web API because the Web API handles only routes it can match in your route definitions. Everything else propagates as a 404 Exception. Its handling then is a matter of the hosting environment, which I suppose in your case is ASP.NET (since you mentioned something about ASP.NET MVC) Commented Jan 22, 2014 at 21:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried using an Exception Filter? This may allow you to capture exceptions and then set the response type "applications/json", message, etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.