c# - ASP.NET Web Api 中的 Swagger 参数过滤器
问题描述
我有 ASP.NET Core 应用程序,我可以在其中扩展 swagger 枚举,
public class MyParameterFilter : IParameterFilter
{
/// <inheritdoc />
public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
{
var routeInfo = context.ApiParameterDescription.RouteInfo;
if (routeInfo?.Constraints != null && routeInfo.Constraints.Any(c => c is MyConstraint))
{
parameter.Schema.Enum = Myvalues.Select(p => new OpenApiString(p)).ToList<IOpenApiAny>();
}
}
}
现在我想在我的经典 ASP.NET Web Api 项目中做同样的事情,我看到 DocumentFilter、OperationFilter 和 SchemaFilter 但没有 ParameterFilter。我的意思是我找不到 IParameterFilter
解决方案
使用的文档过滤器,
public class MyDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
var pathItems = swaggerDoc.paths.Values;
var deletes = pathItems.Select(pathItem => pathItem.delete).Where(o => o?.parameters != null);
var gets = pathItems.Select(pathItem => pathItem.get).Where(o => o?.parameters != null);
var heads = pathItems.Select(pathItem => pathItem.head).Where(o => o?.parameters != null);
var patches = pathItems.Select(pathItem => pathItem.patch).Where(o => o?.parameters != null);
var puts = pathItems.Select(pathItem => pathItem.put).Where(o => o?.parameters != null);
var posts = pathItems.Select(pathItem => pathItem.post).Where(o => o?.parameters != null);
var options = pathItems.Select(pathItem => pathItem.options).Where(o => o?.parameters != null);
var allOperations = deletes.Concat(gets)
.Concat(heads)
.Concat(patches)
.Concat(puts)
.Concat(posts)
.Concat(options)
.ToList();
foreach (Operation operation in allOperations.Where(o => o.parameters.Any(p => p.name == "propName")))
{
operation.parameters.First(p => p.name == "propName").@enum = MyValues.Select(p => (object)p.Name).ToList();
var successResponse = operation.responses.First(d => d.Key == "200").Value;
if (successResponse == null)
{
return;
}
successResponse.examples = MyValues.ToDictionary(d => d.Name, d => "string");
}
}
}
推荐阅读
- android - 设计 - 使用 com.github.mikephil.charting
- vue.js - vue 的 vue-dat-gui 不适用于“无法读取未定义的属性 '_c'”错误消息
- npm - 如何解决 npm install 的错误代码 1
- javascript - Chrome.storage.sync.get 在另一个 .js 文件中
- flutter - Flutter 中的 const 构造函数和 const 对象
- javascript - 在多个画布的 p5js 实例模式下,未定义 p5 对象
- c# - 为什么 File.ReadAllLinesAsync 会阻止 WPF 中的 UI 线程?
- orleans - 奥尔良谷物的一对多组合
- c# - 具有不同分辨率后缀的剧集标题的正则表达式匹配
- c# - 如何将 ListView 中的图像定位在列的左侧?