Asp.net
何時以及如何使用回复________是pe(typeof(…))R和sp這ns和噸是p和(噸是p和這F(…))ResponseType(typeof(…))正確嗎?
我正在做一個項目,我有一個帶有
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(); }另請參閱自定義 Swashbuckle 以及如何使用 ResponseType 屬性來確定文件https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-dotnet-swashbuckle-customize/