我正在研究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所示的响应模式的示例
但是实际的包装响应看起来像,
是否有可能使用Swashbuckle.AspNetCore 5.0.0
处理这些打包的响应。请帮助我。
经过一些分析和研究,我找到了解决方案。使用[ProducesResponseType]
属性非常简单。
我创建了一个单独的名为class
的ResponseWrapper<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()
...
而且可行。希望这对某人有帮助。