Cra*_* W. 6 c# asp.net-web-api asp.net-web-api2
我已经看到从Web API以两种不同的方式发送响应.
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
Run Code Online (Sandbox Code Playgroud)
要么
return StatusCode(HttpStatusCode.UnsupportedMediaType);
Run Code Online (Sandbox Code Playgroud)
两人最终都会向调用者发回415.我已经查看了两个结果类的MSDN文档,但仍然无法弄清楚有什么不同或为什么我会选择一个而不是另一个.
使用StatusCodeResult,方便单位可测试性。
示例(在 xUnit 中):
var result = Assert.IsType<StatusCodeResult>(valuesController.Blah(data));
Assert.Equal(415, result.StatusCode);
Run Code Online (Sandbox Code Playgroud)
回应评论:我更喜欢以下内容:
public IHttpActionResult Get(int id)
{
if(id == 10)
{
return StatusCode(HttpStatusCode.NotFound);
}
return Ok("Some value");
}
Run Code Online (Sandbox Code Playgroud)
而不是:
public IHttpActionResult Get(int id)
{
if(id == 10)
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound));
}
return Ok("Some value");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7647 次 |
| 最近记录: |