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

相关推荐
追逐时光者8 小时前
精选 8 款 .NET 开源、前后端分离的快速开发框架,提高开发生产效率!
后端·.net
航Hang*11 小时前
Photoshop 图形与图像处理技术——第1章:数字图像基本知识
图像处理·笔记·ui·photoshop
长空任鸟飞_阿康13 小时前
MasterGo AI 实战教程:10分钟生成网页设计图(附案例演示)
前端·人工智能·ui·ai
安得权17 小时前
.NET 把文件上传到Sharepoint - Microsoft Graph API方式
microsoft·.net·sharepoint
Xiaobaiforgod18 小时前
产品 & UI/UX
ui·产品经理·ux
薛勇19 小时前
.net中如何选择async/await 和Task.Run?
c#·.net
航Hang*20 小时前
Photoshop 图形与图像处理技术——第3章:图像的选择与填充
图像处理·笔记·ui·photoshop
l1m0_20 小时前
UI设计规范工程化,AI生成Ant Design设计稿流程拆解
人工智能·ui·产品经理·设计·arco design·设计规范
温暖的苹果20 小时前
【.Net runtime】coreclr(.Net应用启动过程)
c#·.net·.netcore