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

相关推荐
The_superstar68 小时前
陶晶驰串口屏使用
ui·串口屏·串口通讯·ui设计·lcd显示
专注VB编程开发20年9 小时前
流式解压 + 分块处理 + 增量安装
.net
工业HMI实战笔记16 小时前
工业机器人HMI:协作机器人的人机交互界面
人工智能·ui·性能优化·机器人·自动化·人机交互·交互
HwJack201 天前
HarmonyOS APP UI单位适配深度实践:vp/fp/px的工程化解决方案分享
ui·华为·harmonyos
工业HMI实战笔记1 天前
工业HMI色彩规范:4个禁忌+3类场景配色方案
ui·性能优化·自动化·汽车·交互
guizhoumen2 天前
liunx环境手动安装.net8的教程
.net
csdn_life182 天前
Qwen3.5-397B-A17B-GGUF(UD-Q4_K_XL)3卡全流程部署文档(基础→API→UI)
ui
工控小龙人2 天前
环保设备HMI:废气处理的浓度监控界面
ui·人机交互·用户界面
疯狂敲代码的老刘2 天前
如何在 TRAE 中安装 UI/UX Pro Max Skill?完整图文教程
ui·ux·trae·skills
全栈小52 天前
【C#】.net 6.0和8.0有什么区别,以及8.0增加了那些功能,这些功能有那些作用
开发语言·c#·.net