Using HttpContext.Current in ASP.NET WebAPI

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

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

However, it seems to ApiControllerhave no property Response. Is there a reason for this? Can it just be used HttpContext.Current.Responseas follows :?

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

Or is there a specific way to record a response from a WebAPI controller?

+5
source share
2 answers

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

HttpResponseMessage CLR, HTTPResponseException 404.

+7

, , Request.CreateErrorResponse . , , CustomErrors ON web.config DEBUG. , HttpConfiguration.IncludeErrorDetailPolicy. : http://weblogs.asp.net/cibrax/archive/2013/03/01/asp-net-web-api-logging-and-troubleshooting.aspx

, , , : -API, HttpError - "

0

All Articles