.Net5中Swagger采用Attribute方式实现Api隐藏

学更好的别人,

做更好的自己。

——《微卡智享》

本文长度为2041,预计阅读6分钟

前言

前面的《使用.Net5尝鲜的一些小总结及Configuration.Json读取配置文件的使用》文章中简单说过.Net5的项目自动集成了Swagger中间件,对做Api接口进行测试方便了很多,平时做程序人的人应该也都会有这样的经历,写了不少代码或是API后,可能用不到,直接把代码删了会可惜,万一以后用到了呢,但是显示出来太多测试也比较麻烦,所以这篇就来说说怎么让Swagger的API实现部分隐藏。

实现效果

隐藏前

隐藏后

从上面两图中可以看到,在Test的Controller中原本是有三个API的,使用了隐藏后最后只有一个Api显示在外面。实现在Swagger中隐藏Api的方式我们就利用到了特性Attribute,关于特征在《【干货】C#自定义特性(Attribute)讲解与实际应用》有详细的讲解,可以直接看那篇文章来了解c#中的特性。

实现思路

#Swagger隐藏Api
1创建一个IDocumentFilter的继承类,实现隐藏接口特性标识
2在Startup的ConfigureServices中针对AddSwaggerGen的项中加入DocumentFilter的过滤
3在想要隐藏的Api上面加入我们定义好的特性

代码实现

微卡智享

01

创建IDocumentFilter类

在项目中创建了一个SwaggerApi的类,继承自IDocumentFilter

实现上图红框中Apply的接口方式,然后再添加一个方法如上图蓝框中,用于标识隐藏特性。

using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;


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




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


02

修改Startup启动项

在Startup的类中ConfigureServices方法中针对services.AddSwaggerGen中再加入一行代码用于实现过滤API

  //新加入代码
c.DocumentFilter<SwaggerApi>();

03

对隐藏的API加入特性

最后我们只要对想要隐藏的Api加上特性,即可实现隐藏效果了。

上图中可以看到,我们在Test的控制器中前两个方法里加入了[SwaggerApi.HideApi]特性,而这个特性就是定义的SwaggerApi的新加入的那个HideApi的方法,如下:

这样我们就可以实现文章开头里隐藏后的界面效果。

扫描二维码

获取更多精彩

微卡智享

「 往期文章 」

C++ OpenCV透视变换改进---直线拟合的应用

C++ OpenCV透视变换综合练习

.net5发布在Windows2008的几个注意事项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vaccae

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值