首页 > 代码库 > Swagger 增加 DocumentFilter 隐藏不需要显示的接口

Swagger 增加 DocumentFilter 隐藏不需要显示的接口

services.ConfigureSwaggerGen(options => {	options.SingleApiVersion(new Info {		Version = "v1",		Title = "xxx API",		Description = "xxx 项目webapi接口说明",		TermsOfService = "None",		Contact = new Contact { Name = "xxx", Email = "", Url = "http://xxx.com" },		License = new License { Name = "xxx", Url = "http://xxx.com" }	});	options.IncludeXmlComments(AppContext.BaseDirectory + @"/Admin.xml"); // 这个需要开启项目生成 xml 选项	options.DocumentFilter<HiddenApiFilter>();	// 在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成});
HiddenApiFilter.cs 代码实现部分

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]public partial class HiddenApiAttribute : Attribute { }public class HiddenApiFilter : IDocumentFilter {	public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) {		foreach (ApiDescription apiDescription in context.ApiDescriptionsGroups.Items.SelectMany(e => e.Items)) {			if (apiDescription.GetControllerAttributes().OfType<HiddenApiAttribute>().Count() == 0 				&& apiDescription.GetActionAttributes().OfType<HiddenApiAttribute>().Count() == 0) continue;			var key = "/" + apiDescription.RelativePath.TrimEnd(‘/‘);			if (!key.Contains("/test/") && swaggerDoc.Paths.ContainsKey(key))				swaggerDoc.Paths.Remove(key);		}	}}

 

Swagger 增加 DocumentFilter 隐藏不需要显示的接口