【发布时间】:2016-03-23 23:27:27
【问题描述】:
我正在寻找一种在 Swagger 文档中以可配置的方式使用 SwashBuckle 显示/隐藏 WebAPI 路由的方法。添加[ApiExplorerSettings(IgnoreApi = true)] 确实会隐藏路线,但每次我想要更改时都需要重新编译。
我已经研究过创建一个IOperationFilter 来使用我定义的自定义属性。这样我就可以用[SwaggerTag("MobileOnly")] 装饰路线并检查web.config 或其他东西以查看是否应该显示路线。属性定义如下:
public class SwaggerTagAttribute : Attribute
{
public string[] Tags { get; private set; }
public SwaggerTagAttribute(params string[] tags)
{
this.Tags = tags;
}
}
这里定义了检测属性的IOperationFilter和删除路径的IDocumentFilter:
public class RemoveTaggedOperationsFilter : IOperationFilter, IDocumentFilter
{
private List<string> TagsToHide;
public RemoveTaggedOperationsFilter()
{
TagsToHide = ConfigurationManager.AppSettings["TagsToHide"].Split(',').ToList();
}
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var tags = apiDescription.ActionDescriptor
.GetCustomAttributes<SwaggerTagAttribute>()
.Select(t => t.Tags)
.FirstOrDefault();
if (tags != null && TagsToHide.Intersect(tags).Any())
{
operation.tags = new List<string> {"Remove Me "};
}
}
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
foreach (var value in swaggerDoc.paths.Values)
{
if (value.post != null && value.post.tags.Contains("Remove Me"))
value.post = null;
if (value.get != null && value.get.tags.Contains("Remove Me"))
value.get = null;
if (value.put != null && value.put.tags.Contains("Remove Me"))
value.put = null;
if (value.delete != null && value.delete.tags.Contains("Remove Me"))
value.delete = null;
}
}
}
并这样注册:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<RemoveTaggedOperationsFilter>();
c.DocumentFilter<RemoveTaggedOperationsFilter>();
});
我觉得当我更早地访问它时标记某些东西以便稍后删除它是低效和hacky的。有什么方法可以让我从IOperationFilter.Apply 中删除路由,而不是等待IDocumentFilter 并扫描它?
【问题讨论】:
标签: c# asp.net-web-api swagger custom-attributes swashbuckle