1 回答
TA贡献1833条经验 获得超4个赞
解决了。您只需要实施IOperationFilter并注册它。这个东西允许您为同一模型显示定制的不同示例。
数据传输协议
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>();
- 1 回答
- 0 关注
- 60 浏览
添加回答
举报