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

相关推荐
BU摆烂会噶1 小时前
【LangGraph】节点内调用与状态隔离
android·人工智能·python·ui·langchain·人机交互
努力努力再努力wz2 小时前
【C++高阶数据结构系列】:时间轮定时器详解:原理分析与代码实现,带你从零手撕时间轮!(附时间轮的实现源码)
c语言·开发语言·数据结构·c++·qt·算法·ui
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_58:(构建行星数据表——HTML表格高级实战指南)
前端·javascript·ui·html·音视频
BU摆烂会噶2 小时前
【LangGraph】作为节点添加与状态共享
android·人工智能·python·ui·langchain·人机交互
ZC跨境爬虫4 小时前
跟着 MDN 学 HTML day_60:(表单与按钮技能测试实战)
服务器·前端·javascript·数据库·ui·html
richard_yuu5 小时前
鸿蒙ArkUI组件化实战|公共组件封装、复用解耦与上架级UI规范落地
ui·华为·harmonyos
ZC跨境爬虫6 小时前
跟着 MDN 学 HTML day_59:HTML表单与按钮——构建用户交互的基石
前端·javascript·ui·html·交互·媒体
阿里巴巴淘系技术团队官网博客6 小时前
AI-Generated UI 技术深度解析:模型流式输出与 UI 渲染实践
人工智能·ui
ZC跨境爬虫6 小时前
模块化烹饪小程序开发日记 Day1:项目初始化与模块化目录设计
前端·javascript·ui·微信小程序·音视频
rockey62718 小时前
AScript如何实现LINQ语法
sql·c#·.net·linq·script·eval·expression