C# 在返回任务的方法中返回HttpStatus代码<;列表<;T>&燃气轮机;

C# 在返回任务的方法中返回HttpStatus代码<;列表<;T>&燃气轮机;,c#,asp.net-core,http-status-codes,C#,Asp.net Core,Http Status Codes,如何在返回列表的方法中返回不同类型的HttpStatus代码? 如果方法点击tryblock,它应该返回200(因为它是一个成功的响应,所以会自动发生)。如果遇到catch块,则需要返回404 [HttpGet] [Route("{customerId}")] public async Task<List<CategoryEntity>> GetCategoryByCustomerId(Guid customerId) { try { L

如何在返回列表的方法中返回不同类型的HttpStatus代码? 如果方法点击
try
block,它应该返回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;
    }
}
[HttpGet]
[路由(“{customerId}”)]
公共异步任务GetCategoryByCustomerId(Guid customerId)
{
尝试
{
List categoryEntities=\u categoryRepository.GetAllCategoriesByCustomerId(customerId);
返回类别实体;
}
捕获(例外情况除外)
{
_logger.LogError(例如,例如消息);
返回null;
}
}
[HttpGet]
[路由(“{customerId}”)]
公共异步任务GetCategoryByCustomerId(Guid customerId)
{
尝试
{
List categoryEntities=\u categoryRepository.GetAllCategoriesByCustomerId(customerId);
HttpContext.Response.StatusCode=(int)HttpStatusCode.OK;
返回类别实体;
}
捕获(例外情况除外)
{
_logger.LogError(例如,例如消息);
HttpContext.Response.StatusCode=(int)HttpStatusCode.NotFound;
返回null;
}
}

如果您希望您的方法生成特定的HTTP状态代码,您的方法应该返回一个
IActionResult
ActionResult
类型代表HTTP状态代码()

对于您的方法,您将在try块内返回一个
OkResult
,让该方法用HTTP 200响应,在catch内返回一个
NotFoundResult
,让它用HTTP 404响应


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

这是一个老问题,但我一直遇到这个问题,尽管James基本上给出了答案,我花了很长时间才记住显而易见的一点:只需将ActionResult添加到返回类型级联中,如下所示:

public async Task<ActionResult<List<CategoryEntity>>> GetCategoryByCustomerId(...
公共异步任务GetCategoryByCustomerId(。。。

在您的情况下,您可以返回严格的类型,即列表可以是null或某个值。您需要返回iActhRead结果。然后返回HTTestPosiSE结果与一些内容。您可以考虑创建一个新的响应模式,其属性为“代码>状态代码< /代码>和<代码>实体< /代码>。您不应该返回404个表示URL的状态。资源不存在。
public async Task<ActionResult<List<CategoryEntity>>> GetCategoryByCustomerId(...