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

相关推荐
John_ToDebug8 小时前
WebContent 与 WebView:深入解析浏览器渲染架构的双层设计
c++·chrome·ui
一念一花一世界10 小时前
接口管理工具选型指南:Postman vs swagger vs PostIn
postman·swagger·postin·接口管理工具
小小测试开发10 小时前
UI自动化测试:CSS定位方式超详细解析(附实战示例)
css·ui·tensorflow
光影少年13 小时前
智能体UI ux pro max
前端·ui·ux
波波00713 小时前
Native AOT 能改变什么?.NET 预编译技术深度剖析
开发语言·.net
一叶星殇15 小时前
WPF UI 框架大全(2026版)
ui·wpf
软件聚导航1 天前
马年、我用AI写了个“打工了马” 小程序
人工智能·ui·微信小程序
尤老师FPGA1 天前
使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第四十七讲)
ui
UI设计兰亭妙微1 天前
UI 设计组件的价值与实践+常用 UI 设计组件核心规范清单
人工智能·ui
Crazy Struggle1 天前
.NET 中如何快速实现 List 集合去重?
c#·.net