在dotnet学习中,关于Swagger的XML注释问题

发布时间 2023-09-26 14:16:32作者: 再躺一会儿吧
使用dotnet 的命令创建的webapi项目中, 是有预置swagger的功能, 跟随官网文档引导开启了swaggerXML注释的支持. 发现controller上面的注释没有生效, 查看IncludeXmlComments 方法时发现有一个参数includeControllerXmlComments默认为false
namespace Microsoft.Extensions.DependencyInjection // SwaggerGenOptionsExtensions.cs
 
  // .......
public static void IncludeXmlComments(
  this SwaggerGenOptions swaggerGenOptions,
  string filePath,
  bool includeControllerXmlComments = false)
  {
    swaggerGenOptions.IncludeXmlComments((Func<XPathDocument>) (() => new XPathDocument(filePath)), includeControllerXmlComments);
  }

传入includeControllerXmlCommentstrue并重启,controller的xml注释生效
// Program.cs
// ......
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1",
            new OpenApiInfo { Title = "这是标题", Version = "v1", Description = "这是描述" });
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
        options.OrderActionsBy(o => o.RelativePath);
    });
}