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

本文关键字:代码 成功 NET Web API 控制 ASP | 更新日期: 2023-09-27 18:32:55

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

我的初始控制器结构如下

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

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

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

public Product PostProduct(string id, Product product)
{   
var product= service.CreateProduct(product);
return product;
}

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

关于您在下面的观察:

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与帮助页面包一起安装的文件。它有一个示例,完全适用于像您这样的场景,您可以在其中设置响应的实际类型。

在最新版本(5.0 - 当前为 RC)的 Web API 中,我们引入了一个名为 ResponseType 的属性,您可以使用该属性使用实际类型修饰操作。你将能够将此属性用于你的方案。

我这样做:

[HttpGet]
public MyObject MyMethod()
{
    try
    {
        return mysService.GetMyObject()
    }
    catch (SomeException)
    {
        throw new HttpResponseException(
            new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content =
                        new StringContent("Something went wrong.")
                });
    }
}

如果你没有得到你期望的,抛出一个 HttpResponseException。