【问题标题】:IEnumerable - How to manage NotFound errorIEnumerable - 如何管理 NotFound 错误
【发布时间】:2021-09-08 20:29:57
【问题描述】:

我正在尝试找到一种在 IEnumerable 返回空对象或空数组时返回自定义错误消息的方法

    [HttpGet("All/{questionId}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    // [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)]
    public async Task<IEnumerable<AnswerDto>> GetAnswers(string questionId)
    {
        var answers = await _context.Answers
            .Where(q => q.QuestionId == questionId)
            .ToListAsync();

        // something like this: if (!answers.Any()) return NotFound(new ApiResponse(404), "There are no answers for this question");

        var answersToReturn = _mapper.Map<IReadOnlyList<AnswerDto>>(answers);
        return answersToReturn;
    }

在我的 ApiResponse 类中:

private string GetDefaultMessageForStatusCode(int statusCode)
{
    return statusCode switch
    {
        . . .
        404 => "No item found",
        . . .
    };
}

这方面有什么帮助吗?

【问题讨论】:

标签: c# .net-core async-await


【解决方案1】:

看看controller action return types

ActionResult 有助于返回 HTTP 状态代码,并将生成带有适当 HTTP 状态代码的 Json 结果。

我已经稍微调整了你的代码以适应它 -

[HttpGet("All/{questionId}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    // [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)]
    public async Task<IActionResult<IEnumerable<AnswerDto>>> GetAnswers(string questionId)
    {
        var answers = await _context.Answers
            .Where(q => q.QuestionId == questionId)
            .ToListAsync();

        if (!answers.Any()) return NotFound("There are no answers for this question");

        var answersToReturn = _mapper.Map<IReadOnlyList<AnswerDto>>(answers);
        return Ok(answersToReturn)

【讨论】:

  • 返回的类型不兼容。
  • @Sami-L 我认为您必须从 ControllerBase 继承,但您也可以编写类似 return new OkObjectResult(answersToReturn);return new NotFoundObjectResult("There are no answers for this question"); 的东西
  • @moozywu OkObjectResult 不能用于此返回类型。
  • @Sami-L 为什么不呢?
  • @Sami-L 它去了 tejas-panerkar,我只是好奇是否有技术原因不使用 ActionResult 或 IActionResult :)
猜你喜欢
  • 2017-06-05
  • 2020-11-11
  • 2016-12-16
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2021-07-12
相关资源
最近更新 更多