返回方法中的HttpStatus代码返回Task >

问题描述 投票:0回答:2

如何在返回列表的方法中返回不同类型的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;
    }
}
c# asp.net-core http-status-codes
2个回答
2
投票

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

对于您的方法,您将在try块内返回OkResult,以使该方法响应您的catch内部的HTTP 200和NotFoundResult,以便使用HTTP 404进行响应。

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


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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.