这在项目中有很好的记录:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#include-descriptions-from-xml-comments
包括来自 XML 注释的描述
要使用人性化的描述增强生成的文档,您可以使用 Xml Comments 注释控制器操作和模型,并配置 Swashbuckle 以将这些 cmets 合并到输出的 Swagger JSON 中:
1 - 打开项目的“属性”对话框,单击“构建”选项卡并确保选中“XML 文档文件”。这将在构建时生成一个包含所有 XML cmets 的文件。
此时,任何未使用 XML cmets 注释的类或方法都会触发构建警告。要抑制这种情况,请在属性对话框的“抑制警告”字段中输入警告代码“1591”。
2 - 配置 Swashbuckle 以将文件中的 XML cmets 合并到生成的 Swagger JSON 中:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new Info
{
Title = "My API - V1",
Version = "v1"
}
);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);
}
3 - 使用摘要、备注和响应标签注释您的操作:
/// <summary>
/// Retrieves a specific product by unique id
/// </summary>
/// <remarks>Awesomeness!</remarks>
/// <response code="200">Product created</response>
/// <response code="400">Product has missing/invalid values</response>
/// <response code="500">Oops! Can't create your product right now</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(500)]
public Product GetById(int id)
4 - 您还可以使用摘要和示例标签来注释类型:
public class Product
{
/// <summary>
/// The name of the product
/// </summary>
/// <example>Men's basketball shoes</example>
public string Name { get; set; }
/// <summary>
/// Quantity left in stock
/// </summary>
/// <example>10</example>
public int AvailableStock { get; set; }
}
5 - 重建您的项目以更新 XML 注释文件并导航到 Swagger JSON 端点。请注意描述如何映射到相应的 Swagger 字段。
注意:您还可以通过使用摘要标签注释您的 API 模型及其属性来提供 Swagger Schema 描述。如果您有多个 XML cmets 文件(例如,控制器和模型的单独库),您可以多次调用 IncludeXmlComments 方法,它们将全部合并到输出的 Swagger JSON 中。
仔细按照说明进行操作,您应该会得到如下所示的内容:
https://swashbucklenetcore.azurewebsites.net/swagger/