.net 7 隐藏swagger的api

1.写一个隐藏接口特性表示

复制代码
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

using System.Web.Http.Description;

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


        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (Microsoft.AspNetCore.Mvc.ApiExplorer.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);
                    }
                }
            }
        }
    }

}

2.在porgram.cs中加入option.DocumentFilter<SwaggerApi>();

复制代码
builder.Services.AddSwaggerGen(option =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true);
    option.DocumentFilter<SwaggerApi>();
});

3.使用方法,在controlller前加入SwaggerApi.HideApi即可实现隐藏

4.效果 这里就看不到接口了

相关推荐
搬砖柯5 小时前
系列10-接口/UI 自动化怎么验落库?数据工厂与数据库断言实践
数据库·测试工具·ui·开源·自动化
长孙豪翔6 小时前
在.net中读写config文件的各种方法
java·数据库·.net
GV191rLvq12 小时前
查看w3wp进程占用的内存及.NET内存泄露,死锁分析
.net
界面开发小八哥14 小时前
界面控件DevExpress .NET Reports v26.1新版亮点 - 持续增强可访问性
.net·界面控件·devexpress·ui开发·报表控件
qq_262642371 天前
Swagger/Knife4j 下载文件损坏,但前端却能正常打开
swagger·knife4j·附件下载
工业HMI实战笔记1 天前
工业HMI界面布局“1核2辅”黄金结构,适配90%场景
前端·ui·性能优化·自动化·交互
wei1986211 天前
.net添加web引用和添加服务引用有什么区别?
java·前端·.net
pW3g3lLuu1 天前
.NET 高级开发 | http 接口对接和客户端开发技巧
网络协议·http·.net
CSharp精选营3 天前
.NET 8 与 .NET 9 支持终止倒计时:开发者需要了解什么
.net·lts·.net8·.net9·码农刚子·升级迁移·sts·支持终止
盛夏绽放4 天前
UI UX Pro Max 安装使用
ui·ux·skill