简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM