项目中某个接口不需要显示在swaggerui界面中,该如何实现?
解决方案
新建过滤器HiddenApiFilter
///
/// 隐藏接口,不生成到swagger文档展示
/// 注意:如果不加[HiddenApi]标记的接口名称和加过标记的隐藏接口名称相同,则该普通接口也会被隐藏不显示,所以建议接口名称最好不要重复
///
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public partial class HiddenApiAttribute : Attribute { }
public class HiddenApiFilter : IDocumentFilter
{
///
/// 重写Apply方法,移除隐藏接口的生成
///
/// swagger文档文件
///
/// api接口集合
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
{
if (Enumerable.OfType(apiDescription.GetControllerAndActionAttributes()).Any())
{
string key = '/' + apiDescription.RelativePath;
if (key.Contains('?'))
{
int idx = key.IndexOf('?', StringComparison.Ordinal);
key = key.Substring(0, idx);
}
swaggerDoc.paths.Remove(key);
}
}
}
}
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
//在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成
c.DocumentFilter();
})
.EnableSwaggerUi(c =>
{
});
}
}
参考
文章为作者独立观点,不代表股票交易接口观点