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

相关推荐
测试老哥42 分钟前
UI自动化测试—Jenkins配置优化
自动化测试·软件测试·python·测试工具·ui·jenkins·测试用例
serve the people1 小时前
简化版滑块验证(仅 X 轴滑动 + 美化 UI)
ui
百锦再2 小时前
与AI沟通的正确方式——AI提示词:原理、策略与精通之道
android·java·开发语言·人工智能·python·ui·uni-app
用户4488466710603 小时前
.NET进阶——深入理解线程(1)同步异步与单线程多线程的区分
c#·.net
编程乐趣3 小时前
qdrant-dotnet:官方提供的开源 .NET 客户端库,用于与 Qdrant 向量搜索引擎操作!
c#·.net
Just_Paranoid4 小时前
【Android UI】Android Tint 用法指南
android·ui·tint·porterduff·colorfilter
我是唐青枫4 小时前
告别频繁 GC:C#.NET PooledList 的设计与使用场景
c#·.net
唐青枫4 小时前
C#.NET ref struct 深度解析:语义、限制与最佳实践
c#·.net
reddingtons1 天前
PS 参考图像:线稿上色太慢?AI 3秒“喂”出精细厚涂
前端·人工智能·游戏·ui·aigc·游戏策划·游戏美术
喜欢踢足球的老罗1 天前
Swagger UI 自定义请求头:从用户配置到请求注入的完整流程解析
ui