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

相关推荐
Jeff-Tsai7 小时前
Day 27:Date、DateTime 与 Time 的语义分界
.net·架构设计·erp·definition-driven
sleveen19 小时前
新增办理动词只写 Core:SailFlow 动作骨架、同事务信封与 Sync 钩子自锁治理
开源·.net·工作流·oa引擎
Jeff-Tsai2 天前
Day 26:数值语义、多币种与计量单位
.net·架构设计·erp·definition-driven
风云2 天前
两条 Pipe、五个命门:Vane.NET 内核为什么长这样
开源·网络编程·.net·架构设计·vane.net
zdr尽职尽责2 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
宝桥南山3 天前
Visual Studio 2026新特性 - 可以直接连接DeepSeek(使用Custom Endpoint Provider配置项)
ide·microsoft·微软·aigc·.net·visual studio
Jeff-Tsai3 天前
Day 25:审计轨迹与变更的前后值
.net·架构设计·erp·definition-driven
IT规划师3 天前
Redis 核心机制 | 事务:执行序列的原子性、乐观锁与 8.x 条件写
redis·.net
辰小忆4 天前
11 · RunCurveChart —— 实时运行曲线
c++·ui·duilib
Jeff-Tsai4 天前
Day 24:权限的三轴:动作、行与列
.net·架构设计·erp·definition-driven