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

相关推荐
码观天工7 小时前
AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
ai·.net·milvus·ml.net
白杨攻城狮8 小时前
.net 与 Pythonnet库的使用心得
python·c#·.net
喵叔哟9 小时前
10. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Ocelot 网关--认证
微服务·架构·.net
专注VB编程开发20年9 小时前
VB.NET 如何指定Microsoft Print To PDF的输出路径
microsoft·pdf·.net
h20170106871 天前
C#中的委托是什么?事件是不是一种委托?委托与事件的区别?
开发语言·c#·.net·面试题
唐小墨同学1 天前
Pico 4 Enterprise(企业版)与Unity的交互-打包运行及UI交互篇
ui·unity
白白白白纸呀1 天前
.NET高级应用---自定义Ioc容器(附带源码)
开发语言·c#·.net
_深海凉_1 天前
OmniParser技术分析(一)
深度学习·目标检测·ui·自动化
SchuylerEX1 天前
第三章 组件(12)- 自定义组件类库
前端·c#·.net·blazor·razor·ui框架