Swashbuckle IDocumentFilter 实现 - 如何将 ActionDescriptor.MethodInfo 链接到操作

ste*_*vec 5 c# swagger swashbuckle asp.net-core

  • 项目:ASP Net Core 2.2、Web API
  • 软件包:Swashbuckle.AspNetCore (4.0.1)

我正在编写一个实现Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter,它在我的 swagger 配置文件的路径级别添加 x-summary 值。为此,它需要访问每个 Web 方法的以下两条信息

  1. ApiDescription.ActionDescriptor.MethodInfo - 访问方法的属性
  2. Operation.Summary - 方法的 Xml 注释

看来我可以从提供给 IDocumentFilter 实现的 #1context和 #2 中获取swaggerDoc,但除了使用路径之外,我找不到链接它们的好方法。

有更简洁的方法吗?

下面是我正在做的事情的一个简化示例。

public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
  // Create a map from path (prepended with "/") to the custom attribute
  var methodsByPath = context.ApiDescriptions
    .ToDictionary(
      m => $"/{m.RelativePath}",
      m => ((ControllerActionDescriptor)m.ActionDescriptor).MethodInfo.GetCustomAttribute<MyCustomAttribute>());

  // Add x-summary to each path
  foreach (var pathItem in swaggerDoc.Paths)
  {
    var customAttribute = methodsByPath[pathItem.Key];

    pathItem.Value.Extensions["x-summary"]
      = GeneratePathDescription(pathItem.Value.Post.Summary, customAttribute);
  }
}

string GeneratePathDescription(string methodSummary, MyCustomAttribute attr)
{
  [snip]
}
Run Code Online (Sandbox Code Playgroud)