Swagger UI 隐藏指定接口类或方法
swagger的一个最大的优点是能实时同步api与文档,但有些时候我们不想全部公开接口,而要隐藏或屏蔽一些接口类或方法,swagger也是支持的,
只需要设置一下DocumentFilter方法。
这方面的资源比较少,只找到了博客园nicye的一篇文章
原文地址:http://www.cnblogs.com/kellynic/p/6092879.html#commentform
还有youzi1221对apply方法的改进,使得隐藏接口方法实现。
代码示例:
1.在SwaggerConfig.cs配置文件中设置DocumentFileter
public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { //设置版本和接口描述 c.SingleApiVersion("v1", "接口文档描述"); //设置接口描述xml路径地址 c.IncludeXmlComments(string.Format("{0}/bin/WebAPI.XML", System.AppDomain.CurrentDomain.BaseDirectory)); // 在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成 c.DocumentFilter<HiddenApiFilter>(); c.CustomProvider((defaultProvider) => new CachingSwaggerProvider(defaultProvider)); }) .EnableSwaggerUi(c => { //路径规则,项目命名空间.文件夹名称.js文件名称 c.InjectJavaScript(thisAssembly, "WebAPI.Scripts.swaggerui.swagger_lang.js"); }) ; } }
2.增加HiddenApiFilter.cs类
/// <summary> /// 隐藏接口,不生成到swagger文档展示 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public partial class HiddenApiAttribute : Attribute { } public class HiddenApiFilter : IDocumentFilter { /// <summary> /// 重写Apply方法,移除隐藏接口的生成 /// </summary> /// <param name="swaggerDoc">swagger文档文件</param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer">api接口集合</param> 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("?", StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.paths.Remove(key); } } } }
3.API接口调用实例
/// <summary> /// 隐藏接口方法生成文档(添加[HiddenApi]特性) /// </summary> /// <param name="value"></param> /// <returns></returns> [HiddenApi] [Route("HideApi")] [HttpGet] public HttpResponseMessage HideApi(string value) { return Request.CreateResponse(HttpStatusCode.OK, new { errorCode = "0", value = value }); }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: swagger,从认识swagger到配置
- 下一篇: swagger整合spring mvc教程