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

相关推荐
星尘库22 分钟前
.NET Framework中报错命名空间System.Text中不存在类型或命名空间名Json
java·json·.net
longze_72 小时前
Uigenius:革新 UI/UX 设计的 AI 利器
人工智能·ui·ai·ux·prototype·uigenius
木易 士心2 小时前
Element UI 多级菜单缩进的动态控制:从原理到工程化实践
前端·vue.js·ui
Larry_Yanan4 小时前
Qt线程使用(一)直接继承QThread类
开发语言·c++·qt·ui
遇到困难睡大觉哈哈4 小时前
Harmony os 网络防火墙实战:用 @ohos.net.netFirewall 给应用加一道“网闸”
网络·.net·harmonyos·鸿蒙
搬砖的工人5 小时前
.NET 9.0 与 Swagger 的集成实践:一步步构建Api文档
.net
hellotutu5 小时前
vue2+springboot通过 FormData 手动封装图片数据上传
java·vue.js·spring boot·后端·ui
唐青枫5 小时前
C#.NET Record Struct 完全解析:语法、语义与最佳实践
c#·.net
时光追逐者15 小时前
分享5款.NET开源免费的Redis客户端组件库
数据库·redis·开源·c#·.net·.net core
张人玉1 天前
Prism Template Pack 完整使用示例(VS2022 + .NET 8 + DryIoc)
.net·wpf·prism