Asp.Net Core WebAPI使用Swagger时API隐藏和分组详解(2)

/// <summary> /// 隐藏swagger接口特性标识 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class HiddenApiAttribute:System.Attribute { }

创建API隐藏过滤器HiddenApiFilter继承Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter接口,实现Apply方法

/// <summary> /// 自定义Swagger隐藏过滤器 /// </summary> public class HiddenApiFilter : IDocumentFilter { public void Apply(SwaggerDocument 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 = "https://www.jb51.net/" + apiDescription.RelativePath; if (key.Contains("?")) { int idx = key.IndexOf("?", System.StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.Paths.Remove(key); } } } } }

在Startup.cs中使用HiddenApiFilter

public IServiceProvider ConfigureServices(IServiceCollection services) { ... services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "接口文档", Description = "接口文档-基础", TermsOfService = "", Contact = new Contact { Name = "XXX1111", Email = "XXX1111@qq.com", Url = "" } }); c.SwaggerDoc("v2", new Info { Version = "v2", Title = "接口文档", Description = "接口文档-基础", TermsOfService = "", Contact = new Contact { Name = "XXX2222", Email = "XXX2222@qq.com", Url = "" } }); //反射注入全部程序集说明 GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll") && !t.CodeBase.Contains("Common.Controller.dll")).ToList().ForEach(assembly => { c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml")); }); c.OperationFilter<HttpHeaderOperationFilter>(); c.DocumentFilter<HiddenApiFilter>(); }); ... }

示例:

我这里提供了Consul的心跳检车接口

Asp.Net Core WebAPI使用Swagger时API隐藏和分组详解

但是在接口文档中并没有显示出来

Asp.Net Core WebAPI使用Swagger时API隐藏和分组详解

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdszsz.html