如何在 ASP.NET Core Web API 中的控制器中检查任务结果
How To Check The Task Result In the Controller In ASP.NET Core Web API
我的存储库中有这个:
public async Task<IEnumerable<CatalogModel>> GetCatalogByName(string _UserId, string _CatalogName)
{
var data = await dbcontext.Catalog.Where(x => x.UserId == _UserId).ToListAsync();
return mapper.Map<IEnumerable<CatalogModel>>(data);
}
目前,在我的控制器中:
[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
var task = repository.Catalog.GetCatalogByName(UserId, CatalogName);
return Ok(task);
}
所以现在我一直在 return 正常(任务)。我想检查是否有数据 return 从存储库中编辑,所以我也可以 return NotFound(task)。我似乎不知道该怎么做。
您需要等待 GetCatalogByName
完成才能检查结果。
一个简单的await
就可以了
[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
var task = await repository.Catalog.GetCatalogByName(UserId, CatalogName);
// check task data before return
return Ok(task);
}
但我强烈建议您阅读更多有关 async/await 编程的内容 here
我的存储库中有这个:
public async Task<IEnumerable<CatalogModel>> GetCatalogByName(string _UserId, string _CatalogName)
{
var data = await dbcontext.Catalog.Where(x => x.UserId == _UserId).ToListAsync();
return mapper.Map<IEnumerable<CatalogModel>>(data);
}
目前,在我的控制器中:
[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
var task = repository.Catalog.GetCatalogByName(UserId, CatalogName);
return Ok(task);
}
所以现在我一直在 return 正常(任务)。我想检查是否有数据 return 从存储库中编辑,所以我也可以 return NotFound(task)。我似乎不知道该怎么做。
您需要等待 GetCatalogByName
完成才能检查结果。
一个简单的await
就可以了
[HttpGet]
public IActionResult GetCatalogsByName([FromQuery] string UserId, string CatalogName)
{
var task = await repository.Catalog.GetCatalogByName(UserId, CatalogName);
// check task data before return
return Ok(task);
}
但我强烈建议您阅读更多有关 async/await 编程的内容 here