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

相关推荐
李高钢1 小时前
【WPF】从 Avalon 到 .NET 10:WPF 平台演进史与特性全览
.net·wpf
山川志~2 小时前
Vue + Element UI 实战:如何实现表格时间、金额字段排序
vue.js·ui·elementui
Oll Correct12 小时前
Adobe illustrator 案例六:手枪图标绘制
笔记·ui·adobe·illustrator
l1m0_19 小时前
React+Tailwind+AI 实战:连锁餐饮管理后台从零到一开发复盘
前端·react.js·ui·ai·ai设计
刚子编程1 天前
用 Inno Setup 把 .NET 程序打包成安装包:从零到发布的完整指南
.net·inno setup·码农刚子·.net 程序打包·安装脚本编写
正儿八经的少年1 天前
javaDoc,swagger,springDoc 的作用和区别
swagger·springdoc·javadoc
ryanuo71 天前
Shadcn/ui × Qt 6/QML:一次从 Web UI 到桌面 UI 的组件化实践
c++·qt·ui·shadcn
界面开发小八哥1 天前
界面控件DevExpress Blazor v26.1新版亮点 - TreeList & 数据编辑器
javascript·编辑器·.net·界面控件·blazor·devexpress·用户界面
rockey6271 天前
C#脚本引擎之AScript与Flee对比
c#·.net·script·eval·动态脚本
盛夏绽放2 天前
Proxy与Reflect详解(二):进阶篇——手写Vue3响应式系统
ui·vue3·proxy