接口 Swagger 部分Web API的隐藏


原文:https://www.cnblogs.com/wyt007/p/10650974.html
原文:https://www.bbsmax.com/A/VGzloMNxdb/


一、前言


背景

有的api文档不想显示出来,比如在基类BaseApiController中有一些公用的方法(原因先不管哈)
百度了一下,找到了几篇都是asp.net core的,然后就照着他们的自己稍微改了一下

环境:

  • .NET Framework 4.6.1
  • Swashbuckle 5.6.0



二、具体操作步骤


1、添加特性,隐藏swagger接口特性标识

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class HiddenApiAttribute : Attribute {}

2、添加过滤器,自定义Swagger隐藏过滤器

public class HiddenApiFilter : IDocumentFilter
{      
    void IDocumentFilter.Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
    {
        foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
        {

            if (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);
            }                
        }
    }
}

3、修改SwaggerConfig,注入过滤器

取消注释
c.DocumentFilter<ApplyDocumentVendorExtensions>();
修改为
c.DocumentFilter<HiddenApiFilter>();

4、测试

public class BaseApiController2 : ApiController
{
    [HiddenApi]
    public void test1()
    {

    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM