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

相关推荐
风云9 小时前
从 NLite 到 Vane.Container 1.0:压箱十六年的自研 DI 容器开源
.net·di·mini 容器·nlite
FRing0314 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
Jeff-Tsai17 小时前
Day 21:业务逻辑定制与 Plugin 的四个时点
.net·架构设计·erp·definition-driven
IT规划师17 小时前
Redis 核心机制 | 键生命周期与 TTL 管理
redis·.net
Jeff-Tsai2 天前
Day 20:多语言定制与资源结构
.net·架构设计·erp·definition-driven
xy34532 天前
Axure 9.0 垂直菜单介绍
ui·产品经理·axure·原型设计
Jeff-Tsai3 天前
Day 19:定制层的范围与叠加粒度
.net·架构设计·erp·definition-driven
Oll Correct3 天前
Adobe illustrator 案例十四:花元素标志草图绘制
笔记·ui·adobe·illustrator
Jeff-Tsai4 天前
Day 18:错误契约与用户可见消息
.net·架构设计·erp·definition-driven
IT规划师4 天前
HybridCache-缓存架构决策框架落地
架构·.net