我使用 ASP.NET Core 创建了一个 Web API,并使用 swagger 创建文档。我在 API 端点上使用 XML 注释来提供文档中的附加信息。 swagger配置为:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "MyAPI.xml");
c.IncludeXmlComments(xmlPath);
});
我的 API 端点之一及其 XML 注释是:
/// <summary>
/// Find an existing appointment using the visitor information: First name, last name, email, phone.
/// </summary>
/// <url>http://apiurl/api/appointments/appointmentsByVisitor</url>
/// <param name="criteria">consists of one or more of: Firstname, lastname, email, phone</param>
/// <returns>Existing appointment data in an Appointment object or a business error.</returns>
/// <response code="200">Returns the existing appointment event.</response>
/// <response code="400">Returns if no parameters are specified.</response>
/// <response code="204">Returns if there's no matching appointment.</response>
/// <response code="500">Returns if there's an unhandled exception.</response>
[Authorize]
[HttpGet("appointmentsByVisitor")]
[ProducesResponseType(typeof(Appointment), 200)]
[ProducesResponseType(typeof(BusinessError), 404)]
public IActionResult AppointmentsByVisitor([FromQuery] VisitorSearchCriteria criteria) {}
VisitorSearchCriteria
是一个单独的类,它是 API 端点所需参数的包装器。
public class VisitorSearchCriteria
{
/// <summary>
/// Visitor first name.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Visitor last name.
/// </summary>
public string LastName { get; set; }
// several other properties....
}
此 API 端点的 swagger 文档将 VisitorSearchCriteria 的所有属性显示为参数,但它不选择 XML 注释。请参阅下面的屏幕截图。
如您所见,缺少参数的描述。如何告诉 swagger 使用该外部类中的 XML 注释来创建参数描述?
最佳答案
如果您在不同的项目中定义了模型类,那么您需要转到该项目的属性
,并在构建/输出
下检查“XML 文档文件” :“选项。
然后你需要更新 swagger 配置文件添加。
c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\YourProjectName.xml");
YourProjectName.xml 当然应该包含 XML 格式的模型类字段的描述。
如果您想从不同的项目导入评论,您需要执行与上面相同的操作,添加
c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\YourProjectName2.xml");
到 swagger 配置文件。
请记住,每个项目可能会生成一个 XML 文件,并且您可以将所有这些文件中的注释添加到您的 swagger UI 中。 当您运行 Swagger UI 时,注释应显示在“模型”部分中。
关于asp.net-core - 在 Swagger 中使用属性 XML 注释作为参数描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48305427/