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

相关推荐
wearegogog1233 小时前
C# .NET 文件比较工具 WinForms
开发语言·c#·.net
学以智用3 小时前
.NET Core Swagger 超详细讲解(从入门到企业级)
后端·.net
xiami_world5 小时前
2026年UI/UX设计工具私有化部署方案深度解析
人工智能·ui·ai·产品经理·ux
川石课堂软件测试7 小时前
UI自动化测试|XPath元素定位实践
功能测试·测试工具·jmeter·microsoft·ui·postman·harmonyos
川石课堂软件测试8 小时前
UI自动化测试|CSS元素定位实践
css·测试工具·ui·fiddler·单元测试·appium·harmonyos
云中小生9 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net
步步为营DotNet9 小时前
Semantic Kernel 在.NET AI 开发中的深度探索与实践
人工智能·.net
半亩码田10 小时前
【.NET新特性·第5篇】.NET 9 速览:云原生与性能之年
云原生·.net
.NET修仙日记10 小时前
.NET 领域驱动设计:用户角色更新如何从应用服务落地到领域实体(代码拆解)
c#·.net·领域驱动设计·微软技术·角色设计
ChaITSimpleLove10 小时前
Etl.Net 2.2.0 项目深度分析
数据仓库·.net·etl·大数据处理·数据管道·数据处理引擎