惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
爱范儿
爱范儿
WordPress大学
WordPress大学
Last Week in AI
Last Week in AI
博客园 - 聂微东
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
T
Tailwind CSS Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理
宝玉的分享
宝玉的分享
罗磊的独立博客
Jina AI
Jina AI

博客园 - 毛毛虫

[Maui] 轮子——插件式开发 [Maui] Windows部署 [Maui] 造轮子——LoggerSqlite [Maui] 造轮子——Exception处理 [Maui] 造轮子——MessageBox [Maui] 造轮子——前言、本地化 [C#] 日积月累 [.net10] 极简数据库对象关系映射 [C#] 扩展Enumerable,实现类似Sqlserver的窗口函数lag [Blazor] 学习随笔——呈现约定 [Blazor] 学习随笔——生命周期 [Blazor] 学习随笔——RZ10012警告的处理 [Blazor WebAssembly] 学习随笔——组件1.微信弹框(WXDialog) [Blazor WebAssembly] 学习随笔——身份验证 Asp.net Help ASP.NET Web 应用 Docker踩坑历程——续 [Net6]自己写个消息推送 Docker批处理笔记 ASP.NET Web 应用 Docker踩坑历程
Asp.net6.0 Swagger使用备忘
毛毛虫 · 2022-05-05 · via 博客园 - 毛毛虫

“五一”期间用了一下Swagger,碰到了以下问题:

  1. 如何在Docker中显示OpenApiInfo的中文内容;
  2. 如何显示xml注释;
  3. 如何显示Header;
  4. 如何隐藏ApiController、Action、类或者属性,如何显示枚举

现将解决办法记下留存。

一、在Docker中显示OpenApiInfo的中文内容

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "xxx Api调用说明",
        Description = "巴拉巴拉的一堆描述",
        License = new OpenApiLicense
        {
            Name = "Api调用须知",
            Url = new Uri("http://xxx.com/readmi.html")
        }
    });

});

以上设置的效果

然而发布到Docker以后,中文乱码了(似乎在Program.cs里面输入的中文都会乱码)。我的解决的办法是:
builder.Services.AddSwaggerGen(ProgramHelper.SwaggerSetup);

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace SwaggerDemo;
public static class ProgramHelper
{
    public static void SwaggerSetup(SwaggerGenOptions options)
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "xxx Api调用说明",
            Description = "巴拉巴拉的一堆描述",
            License = new OpenApiLicense
            {
                Name = "Api调用须知",
                Url = new Uri("http://xxx.com/readmi.html")
            }
        });

    }
}

问题解决,但有点脱裤子放屁,不知道有没有不需要脱裤子的方法。

二、显示xml注释

这个微软文档说的很清楚,这里记一下网址备查。

三、如何显示Header

办法如下:

public class SwaggerHeaderAttribute : Attribute { }
public class SwaggerOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.CustomAttributes().Any(ii => ii.GetType() == typeof(SwaggerHeaderAttribute))
            || context.ApiDescription.ActionDescriptor.EndpointMetadata.Any(ii => ii.GetType() == typeof(SwaggerHeaderAttribute)))
        {
            if (operation.Parameters == null)
                operation.Parameters = new List<OpenApiParameter>();

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "Sign",
                In = ParameterLocation.Header,
                Description = "我的签名是这个生成的,巴拉巴拉巴拉",
                Required = true
            });
        }

    }
}

然后在SwaggerSetup里面添加一行
options.OperationFilter<SwaggerOperationFilter>();
在ApiController或者Action前面添加一行[SwaggerHeader]

四、隐藏ApiController、Action、类或者属性,显示枚举

想把1、2隐藏起来,把

public enum ECode
{
    成功,
    [Description("时间戳错误")]
    Timestamp,
    [Description("签名错误")]
    Sign
    
}

显示成3的样子,办法如下:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Enum | AttributeTargets.Field)]
public partial class SwaggerIgnoreAttribute : Attribute { }
public class SwaggerSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {

        #region 给设置了SwaggerIgnoreAttribute特性的类作个标记,以便在DocumentFilter里面移除整个架构
        if (context.Type.GetCustomAttribute<SwaggerIgnoreAttribute>() != null)
        {
            schema.Title = "Remove"; 
        }
        #endregion
        
        else
        {
            if (context.Type.IsEnum)
            {
                #region 设置枚举的描述
                List<string> titleItems = new List<string>();
                foreach (var e in Enum.GetValues(context.Type))
                {
                    if (context.Type.GetField(e.ToString()).GetCustomAttribute<SwaggerIgnoreAttribute>() == null)
                    {

                        titleItems.Add($"{(int)e}:{context.Type.GetField(e.ToString()).GetCustomAttribute<DescriptionAttribute>()?.Description ?? e}");
                    }
                }
                schema.Description = string.Join(";", titleItems);
                #endregion
            }
            else
            {
                #region 移除设置了SwaggerIgnoreAttribute特性的属性
                foreach (var propertyName in context.Type.GetProperties().Where(ii => ii.GetCustomAttribute<SwaggerIgnoreAttribute>() != null).Select(ii => ii.Name))
                    schema.Properties.Remove(propertyName);
                #region
            }
        }

    }
}

public class SwaggerDocFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        //移除在SchemaFilter作了标记的架构
        foreach (var key in swaggerDoc.Components.Schemas.Where(ii => ii.Value.Title == "Remove"))
            swaggerDoc.Components.Schemas.Remove(key);

        #region 移除设置了SwaggerIgnoreAttribute特性的ApiController
        var ignoreApis = context.ApiDescriptions.Where(wh => wh.ActionDescriptor.EndpointMetadata.Any(any => any is SwaggerIgnoreAttribute));
        if (ignoreApis != null)
        {
            foreach (var ignoreApi in ignoreApis)
            {
                swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath);
            }
        }
        #endregion

    }
}

照例需要在在SwaggerSetup里面添加两行
options.SchemaFilter<SwaggerSchemaFilter>();
options.DocumentFilter<SwaggerDocFilter>();
然后给隐藏的内容添加[SwaggerIgnore]

如此,大致达到了我的目的,但存两点不爽:

  • 脱裤子
  • 隐藏类的方式
    若有答案,烦请告知,先谢!