c# - Swashbuckle IDocumentFilter 实现 - 如何将 ActionDescriptor.MethodInfo 链接到 Operation
问题描述
- 项目:ASP Net Core 2.2,Web API
- 包:Swashbuckle.AspNetCore (4.0.1)
我正在编写一个实现Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter
,它在我的 swagger 配置文件的路径级别添加 x-summary 值。为此,它需要访问每个 Web 方法的以下两条信息
- ApiDescription.ActionDescriptor.MethodInfo - 访问方法的属性
- 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]
}
解决方案
您的实现对我来说看起来很整洁,但是如果您正在寻找如何“最好”实现 IDocumentFilter 的示例,请查看 Swashbuckle 的代码:
推荐阅读
- java - Swagger Code Gen Generator 创建了一个扩展数组列表的模型,而 spring fox 没有选择它
- java - 如何从一个类传递一个二维数组以在另一个类中用作参数,以便将它们分类为 2 个 ArrayList
- c# - C# 和 DotNetCore 中项目资源的相对路径
- php - Randomuser.me Foreach Json 结果进入数据库
- ansible - Ansible URI 模块忽略 GET 请求的正文
- linux - 如何删除目录中的文件没有特定正则表达式匹配的目录?
- csv - 如何使用脚本删除 Google 表格中的重复行
- excel - 如何在整个工作表中查找特定值,然后返回找到该值的特定范围
- machine-learning - 朴素贝叶斯 - 没有类别标签 1 的样本
- python - 更新后 pip 保留在旧版本上