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

相关推荐
AI_零食3 分钟前
鸿蒙跨端框架 Flutter 学习 Day 6:Future 在 UI 渲染中的心跳逻辑
学习·flutter·ui·华为·harmonyos·鸿蒙
许泽宇的技术分享17 分钟前
当 AI Agent 遇上 .NET:一场关于智能体架构的技术探险
人工智能·架构·.net
技术与健康40 分钟前
【 Markdown Illustrator - 自动配图系统】
ui·illustrator
AI_零食1 小时前
鸿蒙跨端框架Flutter学习day 2、常用UI组件-弹性布局进阶之道
学习·flutter·ui·华为·harmonyos·鸿蒙
一个帅气昵称啊3 小时前
基于 .NET 的 AI 流式输出实现AgentFramework+SignalR
人工智能·.net
微光守望者3 小时前
Unity小知识【2】:Transform与RectTransform,UI和3D对象的空间转换秘诀
ui·3d·unity
前端世界3 小时前
鸿蒙 UI 为什么会卡?GPU 渲染性能实战分析与优化
ui·华为·harmonyos
呆萌哈士奇16 小时前
告别 throw exception!为什么 Result<T> 才是业务逻辑的正确选择
c#·.net
奔跑的露西ly16 小时前
【HarmonyOS NEXT】ArkUI实现「单格单字符+下划线」手机号/验证码输入框
ui·华为·harmonyos·鸿蒙
招风的黑耳20 小时前
Axure后台管理系统模板:智慧化解决方案的界面设计蓝图
ui·axure·后台原型