如何在返回列表的方法中返回不同类型的HttpStatus代码?如果该方法命中try
阻止它应该返回200(自动它发生,因为它是一个成功的响应)。如果它击中catch
区块,则需要返回404。
[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;
}
}
如果您希望您的方法生成特定的HTTP状态代码,则您的方法应返回IActionResult
。 ActionResult
类型代表HTTP状态代码(ref)。
对于您的方法,您将在try块内返回OkResult
,以使该方法响应您的catch内部的HTTP 200和NotFoundResult
,以便使用HTTP 404进行响应。
您可以将要发送回客户端的数据(即List<T>
)传递给OkResults
的构造函数。
[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;
}
}