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
原文地址:https://www.cnblogs.com/sunshine-wy/p/14549380.html