何时以及如何正确使用[ResponseType(typeof(...))]?

Chr*_*ris 9 asp.net asp.net-web-api asp.net-web-api-routing asp.net-web-api2

我工作的一个项目,我有一个基本的控制器Get(int id),GetElements(),UpdateElement(int id, Element element),AddElement(Element element),DeleteElement(int id).每个方法都使用[Route][Get]...注释和返回IHttpActionResult.

我对[ResponseType(typeof(...))]感到困惑.它是为了什么?何时以及如何正确使用它?

我应该写这样的东西吗? [ResponseType(typeof(IEnumerable<Element>))]GetElements()

谢谢!

JCo*_*ine 10

[ResponseType()]属性有助于创建RESTful Web API以及通过Swagger/Swashbuckle自动生成文档时.

例如,基于id返回项目的方法可以这样写

public YourClass Get(int id)
{
    var item = repo.GetById(id);
    return item;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果找不到该项,它将返回null,而不是404.

所以它可以写得更好

[ResponseType(typeof(YourClass))]
public IHttpActionResult Get(int id)
{
    var item = repo.GetById(id);
    if (item != null)
    {
        return this.Ok(item);
    }

    return this.NotFound();
}
Run Code Online (Sandbox Code Playgroud)

在这里查看更多用途http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing

参考自定义Swashbuckle以及如何responseTyp的属性可以用来确定文档https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

  • 这在撰写本文时是正确的,适用于 MVC 而不是 .NET Core。否决票是不必要的 (3认同)
  • 这应该是 `IActionResult&lt;YourClass&gt;` 并用 `[ProducesResponseType(StatusCodes.Status200OK)]` 和 `[ProducesResponseType(StatusCodes.Status404NotFound)]` 装饰 (2认同)