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

相关推荐
Murphy20239 小时前
.net10 WEB API项目中启用Swagger 页面的配置步骤
swagger·asp.net web api·.net10
FungLeo9 小时前
Flutter 把第三方 UI 库渐进迁回 Material 3:组件映射总表 + 四批次替换实战
flutter·ui
鹤卿12310 小时前
「iOS」天气预报仿写总结
ui·ios·objective-c
猿长大人11 小时前
C# | 函数式编程入门
开发语言·c#·.net
A242073493012 小时前
Vue + TypeScript 请求数据后结合 Element UI 实现树形菜单与下拉选择
vue.js·ui·typescript
头茬韭菜12 小时前
5.5 权限交互:渐进式信任的 UI 设计
ui·交互
L歪歪君 山水甲天1 天前
Office文件的奥秘——.NET平台下不借助Office实现Word、Powerpoint等文件的解析(1)
word·powerpoint·.net
de之梦-御风1 天前
【工业自动化平台】 工程设计-依赖注入控制反转(2)
架构·自动化·.net
imperialeast1 天前
WinAXP音乐播放器8月4日更新
windows·算法·ui
残月心殇 请珍惜枸2 天前
.NET陷阱之五:奇怪的OutOfMemoryException——大对象堆引起的问题与对策
java·jvm·.net