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

相关推荐
兰亭妙微UI设计公司26 分钟前
兰亭妙微UI设计公司:移动端列表页设计的3个要素与2种布局
ui
_李小白2 小时前
【Android UI开发】Android VideoView 使用介绍(一)
android·ui
人丰3 小时前
血泪复盘:一次由 HttpContext.Current 引发的 CPU 100% 惨案
性能优化·.net
Wang's Blog5 小时前
Vibe Coding一人即团队系列23: 基于Stitch/Sketch的UI原型1:1复刻工作流
人工智能·macos·ui·sketch
ChaITSimpleLove7 小时前
用 .NET 10 技术栈 “玩转 AI 学习” 的路线图:从 Minimal API 到 AI Agent 产品
人工智能·.net·学习 ai
我命由我1234518 小时前
UI 设计 7 种排列方式
xml·学习·ui·html·产品运营·产品经理·学习方法
BW.SU1 天前
RUI Studio--嵌入式 UI 开发新范式
单片机·ui·嵌入式开发
半亩码田1 天前
【.NET新特性·第14篇】.NET 10 运行时与 SDK 新特性
.net
skr爱码士1 天前
10_Qt Designer 与 UI 文件(.ui 原理、uic 编译、动态加载)
c++·qt·ui·客户端
祀爱1 天前
C# MQTT 连接服务
后端·c#·.net