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

问题描述 投票:0回答:1
  • 项目: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实现的context中获得#1,并从swaggerDoc中获得#2,但是除了使用路径之外,我找不到链接它们的好方法。

是否有更整洁的方法?

下面是我正在做的简化示例。

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]
}
swagger swashbuckle asp-net-core
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.