.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 小时前
Unity3d中Tab控件的实现
ui·unity·tab·控件
weixin_456904271 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
yuyuyui3 小时前
Roslyn 技术解析:如何利用它做代码规范检查与运行时代码生成?
.net
IDOlaoluo9 小时前
如何安装 NDP48-x86-x64-AllOS-ENU.exe | .NET Framework 4.8 离线安装教程
.net
jz_ddk10 小时前
[LVGL] 从0开始,学LVGL:基础构建篇 - 掌握UI的核心构建块
linux·网络协议·ui·rpc·嵌入式·gui·lvgl
Rhys..10 小时前
python自动化中(包括UI自动化和API自动化)env的作用和使用
python·ui·自动化
追逐时光者10 小时前
使用 Visual Studio 快速创建 NuGet 程序包并发布到 NuGet 官网
后端·.net·visual studio
焚 城14 小时前
.net8.0_webapi 生成二维码
.net
焚 城14 小时前
.NET 程序自动更新的回忆总结
.net
云草桑14 小时前
.net AI MCP 入门 适用于模型上下文协议的 C# SDK 简介(MCP)
ai·c#·.net·mcp