【发布时间】: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",
. . .
};
}
这方面有什么帮助吗?
【问题讨论】:
-
我需要一个涉及 IEnumerable 的案例,正如问题中所建议的那样。
-
@Sami-L 我强烈建议通读this article,以更好地了解何时使用哪种返回类型。
标签: c# .net-core async-await