惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LINUX DO - 最新话题
Recorded Future
Recorded Future
月光博客
月光博客
博客园 - 【当耐特】
博客园 - 叶小钗
宝玉的分享
宝玉的分享
量子位
雷峰网
雷峰网
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
Vercel News
Vercel News
L
LangChain Blog
B
Blog
Y
Y Combinator Blog
爱范儿
爱范儿
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
博客园 - Franky
P
Palo Alto Networks Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
C
Cisco Blogs
Scott Helme
Scott Helme
I
Intezer
T
The Exploit Database - CXSecurity.com
MyScale Blog
MyScale Blog
T
Tor Project blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Troy Hunt's Blog
N
News and Events Feed by Topic
大猫的无限游戏
大猫的无限游戏
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
S
Security Affairs
Cyberwarzone
Cyberwarzone
PCI Perspectives
PCI Perspectives
小众软件
小众软件
D
DataBreaches.Net
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
Forbes - Security
Forbes - Security
S
Securelist
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
The Last Watchdog
The Last Watchdog

博客园 - 轮回

《Vibe Coding 入门宝典:非程序员的AI开发指南》一本改变软件生产方式的开源书 OpenAI API 百度文心大模型API测试 AI工具导航 一键生成dotnet5项目解决方案 倡议发起博客园#爷青回#挑战活动 1024快乐,加班使我快乐,福报如圣光醍醐灌顶! 记一次断电引起的mongodb彻底奔溃【转载】 dotnet core 3.0 swagger 显示枚举描述 dotnet core 项目脚手架这种小事嘛... .net core 2.2 EF oracle db first 不同语言的水仙花性能比较【Test1W】 application.properties详解 --springBoot配置文件【转载】 以太坊客户端Geth命令用法-参数详解【转载】 CentOS7搭建以太坊私有链 【Java编码规范】《阿里巴巴Java开发手册(正式版)》【转载】 SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)【转载】 Eclipse快捷键大全(转载) 在redis一致性hash(shard)中使用lua脚本的坑 如何评价微软Connect 2015?[转载]
dotnet core swagger filter 隐藏接口和显示枚举描述
轮回 · 2019-09-19 · via 博客园 - 轮回

dotnet core 2.2开发项目中,常会使用Swagger UI来生成在线Api文档。

某些接口不想放到Swagger中可以这样写Filter:

    /// <summary> 
    /// 隐藏swagger接口特性标识
    /// </summary> 
    [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)]
    public partial class HiddenApiAttribute : System.Attribute { }

    /// <summary>
    /// 隐藏接口,不生成到swagger文档展示
    /// </summary>
    public class HiddenApiFilter : IDocumentFilter
    {
        /// <summary>
        /// 过滤器
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>

        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (ApiDescription apiDescription in context.ApiDescriptions)
            {
                if (apiDescription.TryGetMethodInfo(out MethodInfo method))
                {
                    if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute))
                            || method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)))
                    {
                        string key = "/" + apiDescription.RelativePath;
                        if (key.Contains("?"))
                        {
                            int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                            key = key.Substring(0, idx);
                        }
                        swaggerDoc.Paths.Remove(key);
                    }
                }
            }
        }
    }

  注意:他不能隐藏一个Controller中的某个Method,比如仅隐藏Post或Get方法,因为它是对路由Paths.Remove

       Starts.cs中加入代码:

c.DocumentFilter<HiddenApiFilter>();

  Controller类或某个方法加入代码:

 [HiddenApi]
 public class ValuesController : ControllerBase
 {
     ...
 }

  显示枚举描述

    /// <summary>
    /// Add enum value descriptions to Swagger
    /// </summary>
    public class EnumDocumentFilter : IDocumentFilter
    {
        /// <inheritdoc />
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            // add enum descriptions to result models
            foreach (var schemaDictionaryItem in swaggerDoc.Definitions)
            {
                var schema = schemaDictionaryItem.Value;
                foreach (var propertyDictionaryItem in schema.Properties)
                {
                    var property = propertyDictionaryItem.Value;
                    var propertyEnums = property.Enum;
                    if (propertyEnums != null && propertyEnums.Count > 0)
                    {
                        property.Description += DescribeEnum(propertyEnums);
                    }
                }
            }
        }

        private static string DescribeEnum(IEnumerable<object> enums)
        {
            var enumDescriptions = new List<string>();
            Type type = null;
            foreach (var enumOption in enums)
            {
                if (type == null) type = enumOption.GetType();
                enumDescriptions.Add($"{Convert.ChangeType(enumOption, type.GetEnumUnderlyingType())} = {Enum.GetName(type, enumOption)},{GetDescription(type, enumOption)}");
            }

            return $"{Environment.NewLine}{string.Join(Environment.NewLine, enumDescriptions)}";
        }
        public static string GetDescription(Type t, object value)
        {
            foreach (MemberInfo mInfo in t.GetMembers())
            {
                if (mInfo.Name == t.GetEnumName(value))
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
                    {
                        if (attr.GetType() == typeof(DescriptionAttribute))
                        {
                            return ((DescriptionAttribute)attr).Description;
                        }
                    }
                }
            }
            return string.Empty;
        }
    }

  Starts.cs中加入代码:

  c.DocumentFilter<EnumDocumentFilter>();

  以上。