在ASP.NET WebAPI中使用HttpContext.Current

jcv*_*dan 5 c# asp.net-mvc asp.net-web-api

我想处理WebAPI操作方法中的异常,通过捕获它们设置状态代码,并将消息写入响应.通常在正常的MVC中Controller我会这样做,使用ControllerResponse属性:

Response.StatusCode = 404;
Response.Write("Whatever");
Run Code Online (Sandbox Code Playgroud)

但似乎ApiController没有任何Response财产.是否有一个原因?可以这样使用HttpContext.Current.Response:?

HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.Write("Whatever");
Run Code Online (Sandbox Code Playgroud)

或者是否有一种特定的方式来写入WebAPI控制器的响应?

Dar*_*ler 7

action方法应该创建响应对象.要么只是做新的HttpResponseMessage,要么调用this.CreateResponse.

如果要返回HttpResponseMessage而不是返回自定义CLR对象,则需要抛出HTTPResponseException以返回404.