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

相关推荐
anling_li4 小时前
《随机乱序键盘》四、简约风格随机乱序键盘案例指南
ui·华为·harmonyos
非酋讨厌5 小时前
.NET 11 Preview 4 正式发布:Runtime-Async 全面启用、Process API 大幅扩展
.net
天天代码码天天14 小时前
工控机还是 Win7?我把 PP-OCRv6 做成了 14MB 纯 CPU DLL,.NET 3.5 也能直接调用
.net·win7·pp-ocrv6
找死的豆腐14 小时前
基于.NET的Windows窗体编程之WinForms图像控件
windows·.net
星释16 小时前
鸿蒙智能体开发实战:27.Skill 测试、发布与管理
ui·华为·log4j·harmonyos·鸿蒙·智能体
anling_li16 小时前
《图片华容道》一、背景设置使用指南
ui·华为·harmonyos
在书中成长17 小时前
HarmonyOS 小游戏《对战五子棋》开发第34篇 - ArkTS中复用UI的方法
ui·harmonyos
爸爸61917 小时前
鸿蒙实战:@State 本地状态与 UI 刷新
ui·华为·harmonyos·鸿蒙系统
sdghterhd17 小时前
当 GIS 开发遇上 .NET:一个 GDAL 集成工具库的架构设计与实践
.net
酷酷的身影19 小时前
Managers/APConfigManager.cs
开发语言·ui·c#