.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 小时前
用 Semantic Kernel 在 .NET 中构建你的第一个 AI 智能体(Agent)
人工智能·.net
七仔啊3 小时前
C#、.NET 、ASP.NET Core、Visual Studio全系列快速入门
c#·asp.net·.net
LabVIEW开发3 小时前
LabVIEW图标编辑器文字模糊现象
ui·编辑器·labview·labview知识·labview功能·labview程序
超龄超能程序猿3 小时前
实战优化:.NET 8 容器 Debian 源+时间同步企业级 Dockerfile
运维·debian·.net
一个帅气昵称啊16 小时前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net
兰亭妙微UI设计公司1 天前
兰亭妙微B端界面设计分享:Vantary海事无人系统任务平台UI/UX设计解析
ui·ux
kyle~1 天前
.NET 软件开发平台
.net
伊玛目的门徒1 天前
deepseek harness DSH 安装皮肤脚手架(dsh‑client‑ui‑skin‑center)踩坑完整记录
ui·插件·皮肤·harness·dsh
一个帅气昵称啊1 天前
.Net C# AI智能体开发-AI智能体
人工智能·c#·.net
zhchyun20082 天前
【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(05)
ui·unity·游戏引擎