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

2024-04-28

  • 项目: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 注释

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

有更简洁的方法吗?

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

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]
}

您的实现对我来说看起来非常简洁,但如果您正在寻找如何“最好”实现 IDocumentFilter 的示例,请查看 Swashbuckle 的代码:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/e2f30e04f412b821a5a989338a186e422c776cc4/src/Swashbuckle.AspNetCore.Annotations/AnnotationsDocumentFilter.cs https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/e2f30e04f412b821a5a989338a186e422c776cc4/src/Swashbuckle.AspNetCore.Annotations/AnnotationsDocumentFilter.cs

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b64b8fd6fbc7959849445be676f5e3d4a8e947bf/src/Swashbuckle.AspNetCore.SwaggerGen/XmlComments/XmlCommentsDocumentFilter.cs https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b64b8fd6fbc7959849445be676f5e3d4a8e947bf/src/Swashbuckle.AspNetCore.SwaggerGen/XmlComments/XmlCommentsDocumentFilter.cs

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swashbuckle IDocumentFilter 实现 - 如何将 ActionDescriptor.MethodInfo 链接到操作 的相关文章

随机推荐