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

相关推荐
喵叔哟2 小时前
65.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--账本合并
.net
xiaoxue..2 小时前
React 新手村通关指南:状态、组件与魔法 UI
前端·javascript·react.js·ui
波波0072 小时前
使用.NET 四步玩转 AI 绘图|不用Python、不买显卡
开发语言·c#·.net
唐青枫2 小时前
深入理解 C#.NET 运算符重载:语法、设计原则与最佳实践
c#·.net
小小测试开发12 小时前
提升App UI自动化性能与效率:从脚本到架构的全链路优化指南
ui·架构·自动化
BW.SU14 小时前
RUI Builder 图形化UI设计工具
ui·hmi·ui设计·ra8889·ra6809·rui·人机界面
用户44884667106018 小时前
.NET进阶——深入理解Lambda表达式(2)手搓LINQ语句
c#·.net
惟恋惜19 小时前
Jetpack Compose 界面元素状态(UI Element State)详解
android·ui·android jetpack
hid5588453619 小时前
vrep/coppeliasim与MATLAB联合仿真:机械臂抓取及运动学动力学轨迹规划
xhtml
_李小白19 小时前
【Android FrameWork】延伸阅读:IGraphicBufferProducer驱动UI绘制过程
android·ui