Return 方法中的 HttpStatus 代码 returns Task<List<T>>

Return HttpStatus code in a method returns Task<List<T>>

如何在 return 列表的方法中 return 不同类型的 HttpStatus 代码? 如果该方法命中 try 块,它应该 return 200(它自动发生,因为它是一个成功的响应)。需要 return 404 如果它击中 catch 块。

[HttpGet]
[Route("{customerId}")]
public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId)
{
    try
    {
         List<CategoryEntity> categoryEntities = _categoryRepository.GetAllCategoriesByCustomerId(customerId);
         return categoryEntities;
    }
    catch (Exception ex)
    {
         _logger.LogError(ex, ex.Message);
         return null;
    }
}
[HttpGet]
[Route("{customerId}")]
public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId)
{
    try
    {
        List<CategoryEntity> categoryEntities = _categoryRepository.GetAllCategoriesByCustomerId(customerId);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return categoryEntities;
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, ex.Message);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
        return null;
    }
}

如果您希望您的方法生成特定的 HTTP 状态代码,您的方法应该 return 和 IActionResultActionResult 类型代表 HTTP 状态代码 (ref)。

对于您的方法,您需要在 try 块中 return 一个 OkResult 来让该方法以 HTTP 200 响应,并在您的 catch 中使用一个 NotFoundResult 来响应它用 HTTP 404 响应。

您可以将要发送回客户端(即您的 List<T>)的数据传递给 OkResults 的构造函数。

这是一个老问题,但我一直 运行 这个问题,尽管 James 基本上给出了答案,但我花了很长时间才记住显而易见的:只需将 ActionResult 添加到您的 Return 类型级联,像这样:

public async Task<ActionResult<List<CategoryEntity>>> GetCategoryByCustomerId(...