首页 > 解决方案 > Swashbuckle IDocumentFilter 实现 - 如何将 ActionDescriptor.MethodInfo 链接到 Operation

问题描述

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

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

似乎我可以从提供给 IDocumentFilter 实现context的 中获得 #1 和 #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]
}

标签: c#asp.net-coreswaggerswashbuckle

解决方案



推荐阅读