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

相关推荐
梦里不知身是客1115 分钟前
flink任务的UI提交方式
大数据·ui·flink
一念一花一世界1 小时前
接口管理工具选型:Postman、Swagger与PostIn的全面对比指南
测试工具·postman·swagger·接口管理工具
程序员杰哥2 小时前
UI自动化测试框架:PO 模式+数据驱动
自动化测试·软件测试·python·selenium·测试工具·ui·测试用例
晚霞的不甘2 小时前
跨端一致性与体验统一:构建面向全场景的 Flutter UI 自适应架构
flutter·ui·架构
用户4488466710604 小时前
.NET进阶——深入理解泛型(4)泛型的协变逆变
.net
步步为营DotNet4 小时前
深度解析.NET中HttpClient的生命周期管理:构建稳健高效的HTTP客户端
网络协议·http·.net
Aevget5 小时前
DevExtreme JS & ASP.NET Core v25.2新功能预览 - 提升AI扩展功能
javascript·人工智能·ui·asp.net·界面控件·devextreme
缺点内向6 小时前
如何在 C# 中高效的将 XML 转换为 PDF
xml·后端·pdf·c#·.net
时光追逐者6 小时前
Visual Studio 2026 正式版下载与安装详细教程!
ide·c#·.net·.net core·visual studio
唐青枫6 小时前
C# 列表模式(List Patterns)深度解析:模式匹配再进化!
c#·.net