在Swagger中将属性XML注释用作参数描述

dev*_*evC 5 xml-comments swagger asp.net-core

我使用ASP.NET Core创建了一个Web API,并用招摇来创建文档。我在API端点上使用XML注释,以在文档中提供其他信息。昂首阔步的配置是:

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);
        });
Run Code Online (Sandbox Code Playgroud)

我的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) {}
Run Code Online (Sandbox Code Playgroud)

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....
}
Run Code Online (Sandbox Code Playgroud)

此API端点的详尽文档显示了VisitorSearchCriteria的所有属性作为参数,但未选择XML注释。请参见下面的屏幕截图。

Swagger参数清单

如您所见,参数的描述丢失了。如何告诉swagger使用该外部类的XML注释来创建参数描述?

小智 9

如果您在不同的项目中定义了一个模型类,那么您需要转到Properties该项目并在Build/Output“XML 文档文件:”选项下进行检查。然后你需要更新 swagger 配置文件添加。

c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\YourProjectName.xml");
Run Code Online (Sandbox Code Playgroud)

YourProjectName.xml 应该包含 XML 格式的模型类字段的描述。

如果您想从不同的项目中导入注释,您需要执行与上述相同的操作,添加

c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\YourProjectName2.xml");
Run Code Online (Sandbox Code Playgroud)

到 swagger 配置文件。

请记住,每个项目可以生成一个 XML 文件,您可以将所有这些文件的注释添加到您的 swagger UI。当您运行 Swagger UI 时,注释应出现在“模型”部分中。


mik*_*123 2

http://wmpratt.com/swagger-and-asp-net-web-api-part-1/

首先,在构建期间启用 XML 文档文件创建。在“解决方案资源管理器”中,右键单击 Web API 项目,然后单击“属性”。单击“构建”选项卡并导航到“输出”。确保检查 XML 文档文件。您可以保留默认文件路径。就我而言,它是 bin\SwaggerDemoApi.XML