如何组合 Swashbuckle 过滤器?
How to combine Swashbuckle filters?
我需要的是使用一些条件来隐藏或显示 Swagger UI 响应的 模型|示例值 中的模型的某些属性。
这是如何实现的?我的条件基于 api 操作的属性和 DTO 的属性。因此,f.e.,如果一个动作提供了一个属性,那么我们应该只在 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>();
我需要的是使用一些条件来隐藏或显示 Swagger UI 响应的 模型|示例值 中的模型的某些属性。
这是如何实现的?我的条件基于 api 操作的属性和 DTO 的属性。因此,f.e.,如果一个动作提供了一个属性,那么我们应该只在 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>();