如何组合 Swashbuckle 过滤器?

我需要的是使用一些条件来隐藏或显示模型中模型的某些属性|Swagger UI 中响应的示例值

这怎么可能实现呢?我的条件基于 api 操作的属性和 DTO 的属性。所以,fe,如果一个动作提供了一个属性,那么我们应该只在 Swagger UI 中看到标记的属性。


30秒到达战场
浏览 61回答 1
1回答

潇潇雨雨

解决了。您只需要实施IOperationFilter并注册它。这个东西允许您为同一模型显示定制的不同示例。数据传输协议public class MyDTO{&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; [ShortModelMember]&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; ...}&nbsp; &nbsp;API控制器中的方法[HttpGet][ReturnShortModel]public MyDTO GetSmthg(){&nbsp; &nbsp; return MyDTO.GetExample();}&nbsp; &nbsp;Swagger的自定义操作过滤器public class SwaggerExcludeFilter : IOperationFilter{&nbsp; &nbsp; public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!apiDescription.GetControllerAndActionAttributes<ReturnShortModelAttribute>().Any())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var responseType = apiDescription.ResponseDescription.DeclaredType;&nbsp; &nbsp; &nbsp; &nbsp; var description = $"OK (uses a short model of {responseType})";&nbsp; &nbsp; &nbsp; &nbsp; var props = responseType&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetProperties()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(p => p.GetCustomAttributes(typeof(ShortModelMemberAttribute)).Any())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToDictionary(p => p.Name, p.PropertyType.Name);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; operation.responses.Clear();&nbsp; &nbsp; &nbsp; &nbsp; operation.responses.Add("200", new Response&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; description = description,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; schema = new Schema&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; example = props,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}&nbsp; &nbsp;最后c.OperationFilter<SwaggerExcludeFilter>();&nbsp; &nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP