Swagger 隐藏具体API
一、why
在swagger ui界面中有时候不想显示某些api,通过下面的方式可以实现。
1.1、新建一个类实现IDocumentFilter接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using Swashbuckle.Swagger; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Description; namespace InvoiceApi.InvoiceHelper { /// <summary> /// 隐藏接口,不生成到swagger文档展示 /// </summary> [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)] public partial class HiddenApiAttribute : System.Attribute { } public class HiddenApiFilter : IDocumentFilter { public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions) { if (Enumerable.OfType<HiddenApiAttribute>(apiDescription.GetControllerAndActionAttributes<HiddenApiAttribute>()).Any()) { string key = "/" + apiDescription.RelativePath; if (key.Contains( "?" )) { int idx = key.IndexOf( "?" , System.StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.paths.Remove(key); } } } } } |
1.2、在SwaggerConfig修改配置
1.3、在想隐藏的api上面添加特性 [HiddenApi]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | using InvoiceApi.InvoiceHelper; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; namespace InvoiceApi.Controllers { public class DownController : ApiController { /// <summary> /// 下载api参数文档 /// </summary> /// <returns></returns> [HttpGet] [HiddenApi] public HttpResponseMessage DownloadDoc() { try { var FilePath = System.Web.Hosting.HostingEnvironment.MapPath( @"~/Doc/api参数说明.docx" ); var stream = new FileStream(FilePath, FileMode.Open); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue( "application/octet-stream" ); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue( "attachment" ) { FileName = "纸质发票参数API文档.doc" , }; return response; } catch { return new HttpResponseMessage(HttpStatusCode.NoContent); } } } } |
本文作者:WangJunZzz
本文链接:https://www.cnblogs.com/WangJunZzz/p/8316587.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步