• swagger中如何隐藏某些接口


      本文涉及技术栈:.net(非.net core)。提前告知是便于大家鉴别这篇文章是否符合自己想要的,好多博客不分.net和.net core,会导致一些小白发现有的代码拿过去根本就运行不通。如果阅读者是别的语言,或者觉得无参考意义也可以移步他处,以此节省您的时间。

      

      以下开始正文:  

      写过webapi的大多用过swagger来生成在线文档,方便调用接口人员的查阅和调试。这里就不介绍如何使用了,底部链接会给出参考资料,帮助您从零开始搭建swagger文档。

      文档生成了,但是由于某些原因,我并不想让我写的某个接口显示在文档里,即这个接口不想暴露给别人,这个可以是我私下自己测试,或者别的什么接口,反正就不想显示出来,出于这个考虑,我找了很多资料,最后得出方案如下:

      第一步,新建过滤器:

    using Swashbuckle.Swagger;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http.Description;
    
    namespace Apps.WebApi.Core
    {
        /// <summary> 
        /// 隐藏接口,不生成到swagger文档展示 
        /// 注意:如果不加[HiddenApi]标记的接口名称和加过标记的隐藏接口名称相同,则该普通接口也会被隐藏不显示,所以建议接口名称最好不要重复
        /// </summary> 
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
        public partial class HiddenApiAttribute : Attribute { }
        /// <summary>
        /// 
        /// </summary>
        public class SwaggerIgnoreFilter : 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);
                    }
                }
            }
    
        }
    }
    View Code

      第二步,swagger的配置文件中注入过滤器:

    using System.Web.Http;
    using Swashbuckle.Application;
    using System.Web;
    using Apps.WebApi;
    using Apps.WebApi.Core;
    
    [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
    
    namespace Apps.WebApi
    {
        /// <summary>
        /// 
        /// </summary>
        public class SwaggerConfig
        {
            /// <summary>
            /// 
            /// </summary>
            public static void Register()
            {
                var thisAssembly = typeof(SwaggerConfig).Assembly;
    
                GlobalConfiguration.Configuration
                    .EnableSwagger(c =>
                        { 
                            c.SingleApiVersion("v1", "Apps.WebApi");
                            c.IncludeXmlComments(string.Format("{0}/bin/Apps.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                            //在接口类、方法标记属性 [HiddenApi],可以阻止【Swagger文档】生成 
                            c.DocumentFilter<SwaggerIgnoreFilter>();
                        })
                    .EnableSwaggerUi(c =>
                        {
                            
                        });
            }
        }
    }
    View Code

       第三步,api带上过滤器属性:

      以上,最后生成的文档就不会显示加了过滤属性的接口了。

      参考资料:

      1.ASP.NET Web API 使用Swagger使用笔记   (PS:这篇文章是帮助您搭建swagger文档,里面关于汉化的代码好像有点小问题,所以我没搞汉化。一般开发也看得懂,如果需要汉化+参考这篇文章也遇到代码错误的,需要另寻方法实现)

      2.c# .Net 让Swagger隐藏/忽略指定接口类或方法  (本文代码基本就是照抄的该文章,只不过是我这里附带了一下图片,阅读性会更好)

    PS:楼主邮箱 tccwpl@163.com
  • 相关阅读:
    9.11 eventbus
    9.10,,,实现new instanceof apply call 高阶函数,偏函数,柯里化
    9.9 promise实现 写完了传到gitee上面了,这里这个不完整
    9.5cors配置代码
    9.5 jsonp 实现
    9.5 http tcp https总结
    9.3 es6 class一部分 and es5 class 发布订阅
    8.30 cookie session token jwt
    8.30vue响应式原理
    warning: LF will be replaced by CRLF in renard-wx/project.config.json. The file will have its original line endings in your working directory
  • 原文地址:https://www.cnblogs.com/sunshine-wy/p/14549380.html
Copyright © 2020-2023  润新知