ASP.NET Web API控制成功代码(200对201)

gov*_*vin 5 .net c# asp.net asp.net-mvc asp.net-web-api

有没有办法为Web API控制器中的方法指定成功返回代码?

我的初始控制器结构如下

public HttpResponseMessage PostProduct(string id, Product product)
{   
var product= service.CreateProduct(product);
return Request.CreateResponse(HttpStatusCode.Created, product);
}
Run Code Online (Sandbox Code Playgroud)

但是,生成Web API帮助页面时,上述方法存在缺陷.Web API帮助页面API无法自动解码强类型产品是响应,因此在其文档中生成示例响应对象.

所以我采用以下方法,但这里的成功代码是,OK (200)而不是Created (201).无论如何,我可以使用一些属性样式语法来控制方法的成功代码?另外,我还想将Location标头设置为创建资源可用的URL - 再次,这在我处理时很容易做到HttpResponseMesage.

public Product PostProduct(string id, Product product)
{   
var product= service.CreateProduct(product);
return product;
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*lla 3

关于您的观察如下:

However, there is drawback to the above approach when you generate Web API help pages. The Web API Help page API cannot automatically decode that the strongly typed Product is the response and hence generate a sample response object in its documentation.

您可以查看HelpPageConfig.cs随 HelpPage 包一起安装的文件。它有一个完全适合像您这样的场景的示例,您可以在其中设置响应的实际类型。

在 Web API 的最新版本(5.0 - 目前为 RC)中,我们引入了一个名为 的属性ResponseType,您可以使用该属性用实际类型来装饰操作。您可以在您的场景中使用此属性。