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

相关推荐
Warson_L10 小时前
.NET 8 速成笔记 1:用 VS Code 做 C# / .NET 开发
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 9:C# 项目常见场景(基础设施篇)
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 8:C# 项目常见业务场景与写法(数据与业务篇)
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 3:作业清单
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 2:C# / .NET 核心概念(结合本项目代码)
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 7:CRUD 速成,10 步加一个新资源
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 6:C# 项目结构与依赖管理
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 0:.NET 与 C# 入门(写给有 Go 基础的你)
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 10:拿到公司的 C# 项目,怎么读、怎么改
c#·.net
Warson_L10 小时前
.NET 8 速成笔记 5:测试
c#·.net