.net 5.0 隐藏swagger接口特性标识
新建一个扩展类HiddenApiFilter,继承IDocumentFilter
/// <summary>
/// 隐藏接⼝,不⽣成到swagger⽂档展⽰
/// </summary>
public class HiddenApiFilter : IDocumentFilter
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public partial class HiddenApiAttribute : System.Attribute { }
/// <summary>
/// 隐藏swagger特性标识
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
foreach (ApiDescription apiDescription in context.ApiDescriptions)
{
if (apiDescription.TryGetMethodInfo(out MethodInfo method))
{
if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)) ||
method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)))
{
string key = "/" + apiDescription.RelativePath;
if (key.Contains("?"))
{
int idx = key.IndexOf("?", System.StringComparison.Ordinal);
key = key.Substring(0, idx);
}
swaggerDoc.Paths.Remove(key);
}
}
}
}
}
添加startup注册代码
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddRazorPages();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication1", Version = "v1" });
c.CustomSchemaIds(type => type.FullName); // 解决相同类名会报错的问题
//API接口文件路径
var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "WebApplication1.xml");
c.IncludeXmlComments(filePath);
//添加对控制器的标签(描述)
c.DocumentFilter<ApplyTagDescriptions>();
//隐藏api
c.DocumentFilter<HiddenApiFilter>();
});
services.AddMvc();
}