.NET 7 API中Result<T>无法被Swashbuckle.AspNetCore识别的问题
.NET 7中Results类型无法被EndpointsApiExplorer识别导致Swagger缺失响应信息的问题
根据微软官方文档,Result<T>系列类型本应无需添加[ProducesResponseType]特性,就能让API文档工具自动识别响应类型和状态码,但在.NET 7版本中,Swashbuckle依赖的EndpointsApiExplorer组件无法正确识别Results<>类型,导致生成的Swagger规范缺失响应信息。
问题复现代码(无响应信息的情况)
使用Results<Ok<WeatherForecast[]>, NotFound>作为返回类型时,生成的Swagger不会记录WeatherForecast响应类型和404状态码:
[HttpGet(Name = "GetWeatherForecast")] public Results<Ok<WeatherForecast[]>, NotFound> Get() { return TypedResults.Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray()); }
正常工作的代码(带正确Swagger响应)
改用IActionResult并手动添加[ProducesResponseType]特性后,Swagger规范会正确包含类型化响应和状态码:
[HttpGet(Name = "GetWeatherForecast")] [ProducesResponseType(typeof(WeatherForecast[]), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public IActionResult Get() { return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray()); }
内容的提问来源于stack exchange,提问作者Jeremy Morren
相关产品推荐
相关产品推荐

