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)
参考自定义Swashbuckle以及如何responseTyp的属性可以用来确定文档https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/
| 归档时间: |
|
| 查看次数: |
9162 次 |
| 最近记录: |