You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:10:36