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

相关推荐
wuyk5552 小时前
PyQt6-第05讲-QtDesigner工作流与ui文件
python·ui·pyqt
Meta Luo3 小时前
UI 自动化测试中的等待、超时和异步加载怎么处理
功能测试·测试工具·ui·回归·自动化
Light Gao5 小时前
AI 对话助手如何实现动态交互?一文讲清 AG-UI、SSE、组件与工具调用
人工智能·ui·交互·大语言模型·sse·智能体·ag-ui
MicrosoftReactor8 小时前
技术速递|当聊天框不再是合适的交互界面
ui·ai·copilot·canvas
秋名山小白10 小时前
UI自动化-Airtest框架落地实战
运维·ui·自动化
const_qiu11 小时前
第 2.5 章 2.5.8:质量关 —— 安全审查、UI/UX 审查与踩坑复盘
java·人工智能·安全·ui·ux
csdn_aspnet12 小时前
C# .NetCore Swagger ISchemaFilter 注入示例值、描述
c#·.netcore·swagger
Autumn_ing1 天前
Design.md生成UI怎么验收?举例运营后台的颜色、状态和数据核对
前端·ui·ai·设计系统·paico·ai生成ui·design.md
特立独行的猫a1 天前
仓颉语言UI开发实战:我用仓颉写了个桌面版力扣
算法·leetcode·ui·tauri·仓颉·cj-tarui