如何使用Swagger

时间:2017-04-17 12:41:14

标签: c# asp.net-core swagger swagger-ui

我有一个示例输入模型如下:

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

这个值将来自UI,我可以使用哪种注释与swagger尽可能多地描述这个API模型?

1 个答案:

答案 0 :(得分:3)

您根本无法使用多个注释来描述模型。您主要描述API本身

  • [HttpGet][HttpPost]用于http属性
  • [Produces(typeof(CarInputModel)]表示操作的返回类型,[ProducesResponseType(typeof(CarInputModel), (int)HttpStatusCode.OK)]表示基于http代码的结果类型(即错误时返回不同的模型)
  • 路线本身
  • [Route]

此外,您可以使用Xml Docs来描述类及其参数。

/// <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; }
}

要使用XmlDoc,您需要在项目设置(以及模型)中启用xml文档的编译,然后将其添加到Startup.cs

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