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