【问题标题】:How to document a wrapped response to be displayed in swagger ui using a Swashbuckle in asp.net core web api如何使用 asp.net 核心 web api 中的 Swashbuckle 记录要在 swagger ui 中显示的包装响应
【发布时间】:2020-06-24 15:54:02
【问题描述】:

我正在处理一个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"  
    ]  
}    

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

根据[ProducesResponseType(200, Type = typeof(IEnumerable&lt;WeatherForecast&gt;))] 在 swagger ui 中显示的响应架构示例

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

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

【问题讨论】:

  • 这是一个奇怪的中间件,我感觉应该都在响应头而不是正文上
  • 是的,我理解并同意。我最近加入了一个项目,他们有这样的项目在生产中,他们不想违反合同。因此我正在这样做

标签: swagger asp.net-core-webapi swashbuckle asp.net-core-3.1 swashbuckle.aspnetcore


【解决方案1】:

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

我创建了一个单独的class,名为ResponseWrapper&lt;T&gt;

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

    public string Message { get; set; }

    public T Result { get; set; }
}

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2019-08-04
    • 2020-09-09
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多