c# - 如何组合 Swashbuckle 过滤器?
问题描述
我需要的是使用某些条件来隐藏或显示模型中模型的某些属性| Swagger UI 中响应的示例值。
这怎么可能实现?我的条件基于 api 操作的属性和 DTO 的属性。所以,fe,如果一个动作提供了一个属性,那么我们应该只在 Swagger UI 中看到标记的属性。
解决方案
解决了。您只需要实现IOperationFilter
并注册它。这些东西允许您为同一模型显示定制的不同示例。
DTO
public class MyDTO
{
public int Id { get; set; }
[ShortModelMember]
public string Name { get; set; }
...
}
API 控制器中的方法
[HttpGet]
[ReturnShortModel]
public MyDTO GetSmthg()
{
return MyDTO.GetExample();
}
Swagger 的自定义操作过滤器
public class SwaggerExcludeFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (!apiDescription.GetControllerAndActionAttributes<ReturnShortModelAttribute>().Any())
{
return;
}
var responseType = apiDescription.ResponseDescription.DeclaredType;
var description = $"OK (uses a short model of {responseType})";
var props = responseType
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(ShortModelMemberAttribute)).Any())
.ToDictionary(p => p.Name, p.PropertyType.Name);
}
operation.responses.Clear();
operation.responses.Add("200", new Response
{
description = description,
schema = new Schema
{
example = props,
},
});
}
}
最后
c.OperationFilter<SwaggerExcludeFilter>();
推荐阅读
- c# - GTK Sharp 同步上下文似乎不存在,默认情况下会中断 async/await
- python - 给定一个数据集,查找它是否是批处理的
- javascript - CRUD - 我无法使用 express 和 mongodb 插入数据
- vue.js - 无法读取未定义的属性“_wrapper”-使用 vue 多选
- visualization - 来自gensim的pyLDAvis可视化未在google colab中显示结果
- delphi - 从 Delphi 10.3 中的 TWebBrowser OnNavigateError 中提取 StatusCode
- php - 从 PHP 显示 PNG 文件
- android - React Native 从您的 react-native 应用程序内部更改设备设置
- python - 具有非常量质量矩阵的非线性微分方程的解
- flutter - 当我在 Flutter 中使用提供程序包将数据从 API 加载到列表中时,它会重复调用 API,我该如何解决?