Asp.net

何時以及如何使用回复________是pe(typeof(…))R和sp這ns和噸是p和(噸是p和這F(…))ResponseType(typeof(…))正確嗎?

  • October 4, 2020

我正在做一個項目,我有一個帶有Get(int id)GetElements()UpdateElement(int id, Element element)AddElement(Element element)的基本控制器DeleteElement(int id)。每個方法都使用[Route]and [Get]… 註釋並返回一個IHttpActionResult.

我很困惑[ResponseType(typeof(...))]。它是乾什麼用的?何時以及如何正確使用它?

我應該寫這樣的東西嗎? [ResponseType(typeof(IEnumerable<Element>))]GetElements()

謝謝!

[ResponseType()]屬性有助於創建 RESTful Web API 以及通過 Swagger / Swashbuckle 自動生成文件。

例如,可以像這樣編寫基於 id 返回項目的方法

public YourClass Get(int id)
{
   var item = repo.GetById(id);
   return item;
}

但是,如果找不到該項目,它將返回 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();
}

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

另請參閱自定義 Swashbuckle 以及如何使用 ResponseType 屬性來確定文件https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

引用自:https://stackoverflow.com/questions/39013973