如何在返回列表的方法中返回不同类型的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;
}
}
答案 0 :(得分:2)
如果您希望您的方法产生特定的HTTP状态代码,则您的方法应返回IActionResult
。 ActionResult
类型代表HTTP状态代码(ref)。
对于您的方法,您将在try块内返回一个OkResult
,以使该方法以HTTP 200响应,并在catch内返回一个NotFoundResult
,以使其通过HTTP 404响应。
您可以将要发送回客户端(即您的List<T>
)的数据传递给OkResults
的构造函数。
答案 1 :(得分:1)
这是一个老问题,但我一直遇到这个问题,尽管 James 基本上给出了答案,但我花了很长时间才记住显而易见的:只需将 ActionResult 添加到您的 Return 类型级联中,如下所示:>
public async Task<ActionResult<List<CategoryEntity>>> GetCategoryByCustomerId(...
答案 2 :(得分:0)
[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;
}
}