2017-04-17 208 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")); 
});