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

相关推荐
MOONICK2 小时前
QT的UI开发框架
qt·ui
宝桥南山12 小时前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
界面开发小八哥21 小时前
界面控件DevExpress Blazor v26.1新版亮点 - Filter Builder等功能升级
ui·界面控件·blazor·devexpress·ui开发
兰亭妙微UI设计公司1 天前
兰亭妙微UI设计:Neemo Project 企业AI项目管理后台全案运营价值解析
人工智能·ui
rockey6271 天前
C#脚本引擎之AScript与DynamicExpresso对比
c#·.net·script·动态脚本
qq_548612452 天前
.NET 平台报表工具汇总(.NET Framework /.NET6-8,中国式复杂报表、Web 嵌入、填报、导出打印)
前端·.net
公子小六2 天前
基于.NET的Windows窗体编程之WinForms音频控件
windows·microsoft·c#·.net·音视频·winforms
枫叶丹42 天前
MCP、A2A、AG-UI:一篇讲清 Agent 协议栈
人工智能·ui·chatgpt·agent·codex
界面开发小八哥2 天前
界面控件DevExpress Blazor v26.1新版亮点 - Navigation(导航)
javascript·.net·界面控件·blazor·devexpress·ui开发
用户298698530142 天前
C# 实现 PowerPoint 多格式转换:图片、PDF 与 SVG 实战
c#·.net·svg