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

相关推荐
宝桥南山7 小时前
Visual Studio - 记录一个Visual Studio 2026(Insiders)的更新问题
windows·microsoft·微软·.net·.netcore·visual studio
Jeff-Tsai8 小时前
Day 30:三段开发深度与框架全图
.net·架构设计·erp·definition-driven
敲上瘾14 小时前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
Jeff-Tsai20 小时前
Day 29:定义、框架与应用代码各负责哪一段
.net·架构设计·erp·definition-driven
2395730491 天前
从 GUI 彻底转向 CLI:我用 .NET + Avalonia + NativeAOT 打造了 Agent 终端托管工具 Octopus
开源·.net·agent·avalonia·ai coding
Jeff-Tsai2 天前
Day 28:DateTime 的时区转换
.net·架构设计·erp·definition-driven
IT规划师2 天前
Redis 核心机制 | Lua 脚本:服务端原子操作·架构决策与生产落地
redis·.net
Jeff-Tsai2 天前
Day 27:Date、DateTime 与 Time 的语义分界
.net·架构设计·erp·definition-driven
sleveen3 天前
新增办理动词只写 Core:SailFlow 动作骨架、同事务信封与 Sync 钩子自锁治理
开源·.net·工作流·oa引擎