.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 小时前
[WinForms] 如何为 .NET Framework 4.8 窗体程序添加自定义图标
visualstudio·c#·.net
甜甜不吃芥末1 小时前
Windows 应用程序的 UI 框架:WPF、WinUI 3 和 UWP的差异区别
windows·ui·wpf
Yan90182 小时前
.net解析雷达拼图3.0组合反射率产品,并按经纬度裁剪绘制组合反射率图
.net
步、步、为营2 小时前
.net服务器Kestrel配置Nginx作为反向代理
服务器·nginx·.net
专注VB编程开发20年2 小时前
各版本操作系统对.NET支持情况(250707更新)
开发语言·前端·ide·vscode·.net
共享ui设计和前端开发人才2 小时前
UI前端大数据可视化实战技巧:如何利用数据故事化提升用户参与度?
ui
蒙小萌19933 小时前
苹果UI 设计
macos·ui·cocoa
界面开发小八哥5 小时前
界面组件DevExpress WPF中文教程:Grid - 如何检查节点?
ui·.net·wpf·界面控件·devexpress·ui开发
我是唐青枫10 小时前
C#.NET serilog 详解
开发语言·c#·.net
UI罐头1 天前
后台设计指南:系统架构、交互规范与工具实战全流程解析
ui·设计·设计工具