【问题标题】:ASP.NET Web API controlling success code (200 versus 201)ASP.NET Web API 控制成功代码(200 与 201)
【发布时间】:2013-10-03 06:39:27
【问题描述】:

有没有办法为 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)。无论如何,我可以使用一些属性样式语法来控制方法的成功代码吗?另外,我还想将 Location 标头设置为创建的资源可用的 URL - 同样,当我处理 HttpResponseMesage 时,这很容易做到。

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

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc asp.net-web-api


    【解决方案1】:

    关于您的以下观察:

    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.

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

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

    【讨论】:

    • 谢谢,成功了。是的,将它与属性路由一起装饰会很好,而不必在不同的地方编写相同的映射。很高兴知道它会在下一个版本中发布。
    • 嗨,在即将发布的 Web API 中,是否还会有一项规定来指定 SuccessResponseType 和 ErrorResponseType 以及它们可能的状态代码列表 - 这样我也可以捕获这些在 API 文档中?
    【解决方案2】:

    我这样做:

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

    如果没有得到预期结果,请抛出 HttpResponseException。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2019-08-01
      • 2013-04-20
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多