Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 449
jcvandan Avatar asked Aug 31 '12 16:08

jcvandan


1 Answers

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.

like image 93
Darrel Miller Avatar answered Oct 07 '22 19:10

Darrel Miller