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

相关推荐
UI设计兰亭妙微7 小时前
飞秒激光时域热反射测量系统软件UI界面设计
ui·ui设计公司
少云清7 小时前
【UI自动化测试】1_IOS自动化测试 _环境搭建
ui·ios
Awna8 小时前
移动端游戏 UI 与动效设计参考指南
游戏·ui
鄃鳕11 小时前
耗时IO对象移到子线程,防止UI卡顿
ui
少云清12 小时前
【UI自动化测试】4_TPshop项目实战 _后台管理-新增商品成功
ui
步步为营DotNet14 小时前
深入理解ASP.NET Core Middleware:构建高效Web应用的关键组件
中间件·asp.net·.net
我是唐青枫14 小时前
C#.NET SignalR 深入解析:实时通信、Hub 与连接管理实战
开发语言·c#·.net
IT 行者15 小时前
每天了解几个MCP SERVER:21st.dev Magic
人工智能·ui·mcp
波波00715 小时前
每日一题:什么是.NET中的线程池?
面试·.net
CodeCraft Studio15 小时前
从车载HMI到数字座舱平台:基于Qt与Qtitan UI组件的汽车嵌入式软件界面开发方案
qt·ui·汽车·嵌入式开发·ui组件·ui框架·数字座舱