首页 > 其他分享 >.net 使用IAsyncResultFilter或IResultFilter 进行restful统一风格在swagger ui中不显示问题解决

.net 使用IAsyncResultFilter或IResultFilter 进行restful统一风格在swagger ui中不显示问题解决

时间:2024-09-04 11:53:21浏览次数:5  
标签:get IAsyncResultFilter schemaGenerator var ui context returnType swagger public

1.现实swagger IOperationFilter 过滤器接口

public class SwaggerOperationFilter: IOperationFilter
{
    private readonly ISchemaGenerator _schemaGenerator;

    public SwaggerOperationFilter(ISchemaGenerator schemaGenerator)
    {
        _schemaGenerator = schemaGenerator;
    }
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // 获取操作返回的类型
        var returnType = context.MethodInfo.ReturnType;

        // 处理 Task<> 或者 ActionResult<>
        if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
        {
            returnType = returnType.GetGenericArguments()[0];
        }

        // 处理 ActionResult<>
        if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ActionResult<>))
        {
            returnType = returnType.GetGenericArguments()[0];
        }
        
        // 动态给泛型添加接口真实返回的类型
        var type = typeof(ApiResponse<>).MakeGenericType(returnType);
        
        // 将描述合并到schema
        var schema = _schemaGenerator.GenerateSchema(type, context.SchemaRepository);

        operation.Responses.Clear();
        operation.Responses.Add("200", new OpenApiResponse
        {
            Description = "统一的成功响应",
            Content = new Dictionary<string, OpenApiMediaType>
            {
                ["application/json"] = new OpenApiMediaType
                {
                    Schema = schema,
                }
            }
        });
    }
}

2.定义返回的泛型类

/// <summary>
/// 全局返回dto
/// </summary>
/// <typeparam name="T"></typeparam>
public class ApiResponse<T>
{
    public string Code { get; set; }
    public bool Success { get; set; }
    public string Message { get; set; }
    public T Data { get; set; }
}

3.在swagger中使用IOperationFilter现实的过滤


            //  注入ISchemaGenerator,  在IOperationFilter实现中构造需要使用
            context.Services.AddTransient<ISchemaGenerator>(provider =>
            {
                var schemaGeneratorOptions = provider.GetRequiredService<SchemaGeneratorOptions>();
                var jsonSerializerOptions = provider.GetRequiredService<ISerializerDataContractResolver>();
                return new SchemaGenerator(schemaGeneratorOptions, jsonSerializerOptions);
            });


            context.Services.AddAbpSwaggerGen(options =>
            {
                 // ...................其他代码省略

                options.OperationFilter<SwaggerOperationFilter>();
                 // ...................其他代码省略
            });

4.效果展示

接口:

swagger:

标签:get,IAsyncResultFilter,schemaGenerator,var,ui,context,returnType,swagger,public
From: https://blog.csdn.net/chinatianmin/article/details/141888993

相关文章

  • 解决podman: ERRO[0000] running newuidmap: write to uid_map failed: Invalid argum
    报错ERRO[0000]running/usr/bin/newuidmap27115520100011100000655366553710000065537:newuidmap:writetouid_mapfailed:InvalidargumentError:cannotsetupnamespaceusing"/usr/bin/newuidmap":shouldhavesetuidorhavefilecapssetu......
  • 『SD』Stable Diffusion WebUI 安装插件(以汉化为例)
    本文简介点赞+关注+收藏=学会了StableDiffusionWebUI是允许用户自行安装插件的,插件的种类有很多,有将页面翻译成中文的插件,也有提示词补全插件,也有精细控制出图的插件。以汉化为例,StableDiffusionWebUI默认是英文的,我们只需装个汉化插件然后重启一下项目就能......
  • [Typescript] Build mode of tsc: tsc -b
    Along-awaitedfeatureissmartincrementalbuildsforTypeScriptprojects.In3.0youcanusethe --build flagwith tsc.Thisiseffectivelyanewentrypointfor tsc thatbehavesmorelikeabuildorchestratorthanasimplecompiler.Running tsc--bui......
  • 【前端面试】采用react前后,浏览器-解析渲染UI的变化
    浏览器渲染html浏览器解析和渲染UI(用户界面),特别是HTML文档,是一个复杂的过程,涉及到多个阶段。以下是浏览器从接收HTML文档到显示渲染后的页面的一般步骤:1.下载HTML文档:用户输入URL或点击链接时,浏览器会向服务器请求HTML文档。服务器响应请求,并将HTML文档......
  • UI自动化如何建立+如何进行元素定位
    下载驱动mac下载驱动的方法seleniummacOSchromedrivermacOS安装Selenium配置ChromeDriver_seleniumide谷歌浏览器驱动下载mac系统-CSDN博客win下载驱动的方法Chromedriver安装教程(简洁版)-CSDN博客驱动-浏览器更新的链接https://www.cnblogs.com/aiyablog/arti......
  • npm install时一直idealTree:npm: sill idealTree buildDeps的解决方案
    修改下镜像的地址。1、采用新的镜像地址,进入cmd之后输入://1.npm的命令npmconfigsetregistryhttps://registry.npmmirror.com//2.yarn的命令yarnconfigsetregistryhttps://registry.npmmirror.com2、查看是否安装成功://npm的命令npmconfiggetregi......
  • SpringBoot3.x+MyBatisPlus+druid多数据源配置
    1引言本章主要介绍SpringBoot3.x多数据源配置,以及在此基础上配置分页拦截,自动填充功等功能,源码链接在文章最后。下面列出几个重要文件进行介绍。2项目结构整体项目结构如下,主要介绍配置文件和配置类。3主要代码3.1pom.xml注意SpringBoot3.x对应依赖为mybatis-plu......
  • 【花雕学编程】Arduino FOC 之并联五连杆算法
    Arduino是一个开放源码的电子原型平台,它可以让你用简单的硬件和软件来创建各种互动的项目。Arduino的核心是一个微控制器板,它可以通过一系列的引脚来连接各种传感器、执行器、显示器等外部设备。Arduino的编程是基于C/C++语言的,你可以使用ArduinoIDE(集成开发环境)来编写、......
  • 【花雕学编程】Arduino FOC 之步进电机正反转驱动、AS5600编码器信息读取及速度检测
    Arduino是一个开放源码的电子原型平台,它可以让你用简单的硬件和软件来创建各种互动的项目。Arduino的核心是一个微控制器板,它可以通过一系列的引脚来连接各种传感器、执行器、显示器等外部设备。Arduino的编程是基于C/C++语言的,你可以使用ArduinoIDE(集成开发环境)来编写、......
  • Stable Diffusion进阶篇,ComfyUI文字生成视频的一条龙服务(附完整工作流)
    有些小伙伴发现了一个问题,那就是根据图片生成出来的视频看着怪怪的:前半段看着好像还可以,但是后面部分的面部就开始崩坏了。而今天这篇笔记则是要简单了解一下一些进阶参数以及一些文生图生视频的内容,不然的话我担心内容太少字数都凑不够。我这里准备了ComfyUI文字生成......