如何使用asp.net core web api中的Swashbuckle记录要在swagger ui中显示的包装响应 [英] How to document a wrapped response to be displayed in swagger ui using a Swashbuckle in asp.net core web api

查看:51
本文介绍了如何使用asp.net core web api中的Swashbuckle记录要在swagger ui中显示的包装响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 ASP.NET Core 3.1 Web api 项目.我正在使用 Swashbuckle.AspNetCore 5.0.0 来记录我的 API.事情进展顺利.但是,由于我的 api 使用中间件来包装每个响应以保持一致性,因此我无法生成响应类型.我无法在我的 swagger ui 中生成正确的响应类型.

I working on a ASP.NET Core 3.1 web api project. I'm using Swashbuckle.AspNetCore 5.0.0 for documenting my API. Things are working good. However I got stuck with generating response types as my api is using an middleware to wrap every response for consistency. I'm not able to generate correct response type in my swagger ui.

这是一个简单的例子,

我的行动方法:

[HttpGet]
[ProducesResponseType(200, Type = typeof(IEnumerable<WeatherForecast>))]
public IEnumerable<WeatherForecast> Get()
...

正如我提到的,该项目有响应中间件,它将按照以下格式包装所有响应,

As I mentioned, the project has response middleware which will wrap all the response as shown in the below format,

{  
    "Version": "1.0.0.0",  
    "StatusCode": 200,  
    "Message": "Request successful.",  
    "Result": [  
        "value1",  
        "value2"  
    ]  
}    

因此,我的 swagger ui 中的响应值不匹配.

Because of this I'm getting mismatch in response value in my swagger ui.

根据 [ProducesResponseType(200, Type = typeof(IEnumerable<WeatherForecast>))]

但实际包装的响应看起来像,

But the actual wrapped response looks like,

是否可以使用 Swashbuckle.AspNetCore 5.0.0 处理这些包装的响应.请帮助我.

Is it possible to handle these wrapped response using Swashbuckle.AspNetCore 5.0.0. Please assist me.

推荐答案

经过一番分析研究,我找到了解决方案.使用 [ProducesResponseType] 属性非常简单.

After some analysis and research, I found the solution. It's pretty simple using the [ProducesResponseType] attribute.

我创建了一个单独的 class 命名为 ResponseWrapper,

I created a separate class named ResponseWrapper<T>,

public class ResponseWrapper<T>
{
    public int StatusCode { get; set; }

    public string Message { get; set; }

    public T Result { get; set; }
}

然后修饰我的action方法如下,

And then decorated my action method as follows,

[HttpGet]
[ProducesResponseType(200, Type = typeof(ResponseWrapper<IEnumerable<WeatherForecast>>))]
public IEnumerable<WeatherForecast> Get()
...

这行得通.希望这对某人有所帮助.

And that works. Hope this helps someone.

这篇关于如何使用asp.net core web api中的Swashbuckle记录要在swagger ui中显示的包装响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆