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

使用ErrorOr返回IActionResult时API报错问题排查

问题分析与解决方案

你的代码错误在于误用了ErrorOr库的异步匹配方法MatchAsync,具体原因和修正方案如下:

错误原因

ErrorOr<T>类型默认提供的是同步的Match方法,只有当你的匹配逻辑内部包含异步操作(比如需要await其他异步方法)时,才需要使用MatchAsync。而你代码中的Ok(value)和BadRequest(errors)都是ASP.NET Core同步返回IActionResult的方法,完全不需要调用异步匹配方法,强行使用MatchAsync会导致编译错误。

修正后的代码

[HttpPost("token", Name = "GenerateToken")]
[ProducesResponseType<GenerateToken.Response>((int)HttpStatusCode.OK)]
public async Task<IActionResult> GenerateToken(GenerateToken.Command command)
{
    var response = await mediator.Send(command);

    return response.Match(
        value => Ok(value),
        errors => BadRequest(errors));
}

补充说明

如果后续你的匹配逻辑需要执行异步操作(例如需要异步写入日志后再返回结果),可以使用MatchAsync,示例如下:

return await response.MatchAsync(
    async value => 
    {
        await _logger.LogInformation("Token generated");
        return Ok(value);
    },
    async errors => 
    {
        await _logger.LogError("Token generation failed");
        return BadRequest(errors);
    });

内容的提问来源于stack exchange,提问作者DrXSsive

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:27:04