如何记录要在asp.net核心网络api中使用Swashbuckle在swagger ui中显示的包装响应

问题描述 投票:0回答:1

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

这是一个简单的例子,

我的操作方法:

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

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

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

因此,我的招摇的用户界面的响应值不匹配。

根据[ProducesResponseType(200, Type = typeof(IEnumerable<WeatherForecast>))],以醒目的UI所示的响应模式的示例

enter image description here

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

enter image description here

是否有可能使用Swashbuckle.AspNetCore 5.0.0处理这些打包的响应。请帮助我。

swagger asp.net-core-webapi swashbuckle asp.net-core-3.1 swashbuckle.aspnetcore
1个回答
0
投票

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

我创建了一个单独的名为classResponseWrapper<T>

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

    public string Message { get; set; }

    public T Result { get; set; }
}

然后按如下所示装饰我的操作方法,

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

而且可行。希望这对某人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.