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

相关推荐
武藤一雄29 分钟前
C# 万字拆解线程间通讯?
后端·微软·c#·.net·.netcore·多线程
赵庆明老师1 小时前
NET 10 集成Session
缓存·.net
kylinmin1 小时前
卸载微软电脑管家:一次性彻底移除
前端·ui·xhtml
SEO-狼术1 小时前
Detect Trends with Compact In-Cell Visuals
.net
赵庆明老师2 小时前
.NET 日志和监控
.net
我是唐青枫2 小时前
C# Params Collections 详解:比 params T[] 更强大的新语法
c#·.net
Zhen (Evan) Wang2 小时前
从客户端的HTTP 请求到后端 .NET 8 API的整个生命周期 - 处理请求和响应的主要方式
c#·.net
zybsjn3 小时前
多线程环境下 Dictionary 高 CPU 问题排查:一次真实的 .NET 线上事故分析
.net
总有刁民想爱朕ha3 小时前
.NET 8 AOT教程的使用
.net·.net8教程
Wiktok4 小时前
【WIT】解决导入pywinauto相关库会导致程序UI界面(tkinter/pyside6)浏览文件等操作卡住问题
python·ui·pywinauto