.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.效果 这里就看不到接口了

相关推荐
公子小六2 小时前
基于.NET的Windows窗体编程之WinForms滑块与上下控件
windows·microsoft·c#·.net·winforms
我命由我123453 小时前
Photoshop - Photoshop 把两个 PSD 文件合并
学习·ui·职场和发展·产品运营·产品经理·学习方法·photoshop
Lost of 程序猿10 小时前
.NET 线程安全集合与并发数据结构深度实战:从 lock 到无锁
数据结构·安全·.net
李游Leo12 小时前
【共创稿事节】 HarmonyOS 7 空间化 UI 实战:从平面布局到空间层级的界面重构
ui·平面·harmonyos
rockey62721 小时前
AScript之编译递归函数
c#·.net·script·动态脚本
图扑可视化1 天前
统一 DataModel 底座,HT UI 组件万物同源|中篇・运笔
ui·数字孪生·组件
陈珙1 天前
.NET AI 实战:用 MCP 把 Claude Code 变成数据库 DBA
架构·.net·技术
星栈独行1 天前
自定义 UI-UX-Pro-Max 的 CSV 知识库,把 AI 生成的后台拉回行业该有的样子
前端·人工智能·ui·ux
geovindu1 天前
CSharp: Template Method Pattern
开发语言·后端·c#·.net·模板方法模式·行为模式
步步为营DotNet1 天前
【MVP深度】.NET MAF:从单 Agent 到可恢复的多 Agent 工作流
.net