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

相关推荐
sg_knight20 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
黄思搏21 小时前
基于标注平台数据的 Unity UI 自动化构建工作流设计与工程实践
ui·unity·蓝湖·vectoui
小樱花的樱花1 天前
1 项目概述
开发语言·c++·qt·ui
2301_822703201 天前
开源鸿蒙跨平台Flutter开发:跨端图形渲染引擎的类型边界与命名空间陷阱:以多维雷达图绘制中的 dart:ui 及 StrokeJoin 异常为例
算法·flutter·ui·开源·图形渲染·harmonyos·鸿蒙
唐青枫1 天前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
c#·.net
会写代码的建筑师1 天前
.NET 控制台后台程序实践细节总结
后端·.net
极梦网络无忧1 天前
Windows UI Automation实现抖音直播间监控(桌面端场控助手核心方案)
windows·ui
newbe365241 天前
Design.md:让 AI 一致性进行前端 UI 设计的解决方案
前端·人工智能·ui
阿捞21 天前
在 .NET 中使用 Moonshot Kimi + AgentFramework:从 SDK 到 Agent 的完整实践
html·.net·xhtml
步步为营DotNet1 天前
解锁.NET 11 中 Microsoft.Extensions.AI 在智能后端开发的深度应用
人工智能·microsoft·.net