异步Web API端点

时间:2016-04-13 10:40:46

标签: c# asynchronous asp.net-web-api

以下Web API端点仍然出现以下错误:

  

“在此前提下开始第二次操作   异步操作完成。“

由于我使用.ToListAsync和实体框架返回的数据,我假设问题是var user行阻塞。

如何使该部分同步?

[Route("Retailers/{search}")]
[HttpGet]
public Task<List<Lookup>> Retailers(string search)
{
    var user = UserManager.FindById(User.Identity.GetUserId());
    Guid userId = Guid.Parse(user.Id);

    var companies = _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail && 
                (c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
                .Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();

    return companies;
}

1 个答案:

答案 0 :(得分:2)

您遗漏了asyncawait个关键字。

  1. async添加到方法签名。
  2. await添加到您对_unitOfWork.GetRepository...ToListAsync()
  3. 的通话中

    代码:

    [Route("Retailers/{search}")]
    [HttpGet]
    public async Task<List<Lookup>> Retailers(string search)
    {
        var user = UserManager.FindById(User.Identity.GetUserId());
        Guid userId = Guid.Parse(user.Id);
    
        var companies = await _unitOfWork.GetRepository<Company>().GetAll().Where(c => c.CompanyType == CompanyType.Retail && 
                    (c.UserID == null || c.UserID == userId) && c.CompanyName.StartsWith(search)).Take(5)
                    .Select(x => new Lookup { Id = x.Id, Name = x.CompanyName }).ToListAsync();
    
        return companies;
    }
    

    作为参考,这里是异步编程的一个很好的链接:Asynchronous Programming with Async and Await