jcvandan
jcvandan

Reputation: 14334

Using HttpContext.Current in ASP.NET WebAPI

I want to deal with exceptions in a WebAPI action method, by catching them setting the status code, and writing a message to the response. Normally in a normal MVC Controller I would do this like so, using Controller's Response property:

Response.StatusCode = 404;
Response.Write("Whatever");

However it seems ApiController doesn't have any Response property. Is there a reason for this? Is it OK to just use HttpContext.Current.Response like this:?

HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.Write("Whatever");

Or is there a specific way of writing to the response from a WebAPI controller??

Upvotes: 5

Views: 8287

Answers (2)

Andy Cohen
Andy Cohen

Reputation: 174

If you want to create a message that describes your exception, your best bet is to call Request.CreateErrorResponse, and use any of the many overloads available. There are caveats to how the response is formatted depending on whether you have CustomErrors set to ON in your web.config, or whether you're in DEBUG mode. You can actually configure this behavior programatically as well, using the HttpConfiguration.IncludeErrorDetailPolicy property. See here as well: http://weblogs.asp.net/cibrax/archive/2013/03/01/asp-net-web-api-logging-and-troubleshooting.aspx

You can read this article for an in depth write up, and some options you have to solve the exact problem you describe: Web API, HttpError and the behavior of Exceptions – ‘An error has occurred’

Upvotes: 0

Darrel Miller
Darrel Miller

Reputation: 142242

The action method is supposed to create the response object. Either just do new HttpResponseMessage or call this.CreateResponse.

If instead of returning the HttpResponseMessage you want to return a custom CLR object then you will need to throw a HTTPResponseException to return a 404.

Upvotes: 7

Related Questions