1

我正在一個項目上工作,我有一個基本的控制器Get(int id),GetElements(),UpdateElement(int id, Element element),AddElement(Element element),DeleteElement(int id)。每個方法使用[Route][Get] ...註釋和返回和IHttpActionResult何時以及如何正確使用[ResponseType(typeof(...))]?

我對[ResponseType(typeof(...))]感到困惑。它是爲了什麼?何時以及如何正確使用它?

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

謝謝!

回答

6

[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/

相關問題