2017-04-17 176 views
0

我有一個例子輸入模型如下儘可能多的描述輸入模型儘可能:如何使用揚鞭

public class CarInputModel { 
    public string Name { get; set; } 
    public string ModelName { get; set; } 
} 

此值將來自UI,我可以大搖大擺的來形容這個API是什麼樣的註解儘可能模型?

+0

請仔細閱讀本http://stackoverflow.com/help/tagging關於如何正確使用標籤的幫助中心文章,以及爲什麼不應該強制標籤變成問題標題 – Tseng

回答

3

根本不能使用很多註釋來描述模型。你主要是描述API本身

  • [HttpGet][HttpPost]爲HTTP屬性
  • [Produces(typeof(CarInputModel)]一個動作的返回類型和[ProducesResponseType(typeof(CarInputModel), (int)HttpStatusCode.OK)]基於HTTP代碼的結果類型(即返回的錯誤不同型號)
  • [Route]爲路線本身

此外,您可以使用Xml文檔來描述類和它們的參數。

/// <summary> 
/// Adds a new car model. 
/// </summary> 
/// <param name="model">The model to add</param> 
/// <response code="201">Returns when the car was added successfully and returns the location to the new resource</response> 
/// <response code="400">Invalid Request data.</response> 
/// <response code="409">Car mode already exists.</response> 
/// <returns>The newly added model on success and a list of errors on failure.</returns> 
[HttpPost] 
[ProducesResponseType(typeof(CarInputModel), (int)HttpStatusCode.Created)] 
[ProducesResponseType(typeof(SerializableError), (int)HttpStatusCode.BadRequest)] 
[ProducesResponseType(typeof(void), (int)HttpStatusCode.Conflict)] 
public IActionResult AddCar(CarInputModel model) 
{ 
} 

/// <summary> 
/// Represents a car 
/// </summary> 
public class CarInputModel { 
    /// <summary> 
    /// Name of the car 
    /// </summary> 
    public string Name { get; set; } 
    /// <summary> 
    /// Model of the car 
    /// </summary> 
    public string ModelName { get; set; } 
} 

爲了使用XmlDocs您需要啓用在您的項目設置的XML文檔的編制方法(和你的模型),然後添加到您的Startup.cs

services.AddSwaggerGen(options => 
{ 
    var appEnv = PlatformServices.Default.Application; 
    options.IncludeXmlComments(Path.Combine(appEnv.ApplicationBasePath, $"{appEnv.ApplicationName}.xml")); 
});