无法使用异步 DocumentDB 操作 CreateDocumentAsync 的结果

Unable to use result of Async DocumentDB operation CreateDocumentAsync

我在Azure上创建了一个documentDB,可以成功创建和获取文档。

但是,虽然在数据库中成功创建了文档,但我无法使用 CreateDocumentAsync 的响应。代码立即 returns 到控制器上的调用方法。所以永远不会到达调试线。

此外,我将 id 设置为 guid,但是 returned 到控制器的文档的 Id 为 1。

控制器

    [HttpPost]
    [Route("")]
    public IHttpActionResult CreateNewApplication(dynamic data)
    {
        if (data == null)
        {
            return BadRequest("data was empty");
        }

        try
        {
            var doc = _applicationResource.Save(data);
            return Ok(doc.Id); //code hits this point and 'returns'
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

资源

  public async Task<Document> Save(dynamic application)
    {
        Document created;

        using (Client)
        {
            application.id = Guid.NewGuid();
            var database = await RetrieveOrCreateDatabaseAsync(Database);
            var collection = await RetrieveOrCreateCollectionAsync(database.SelfLink, CollectionName);

            //persist the documents in DocumentDB
            created = await Client.CreateDocumentAsync(collection.SelfLink, application);

        }

        Debug.WriteLine("Application saved with ID {0} resourceId {1}", created.Id, created.ResourceId);

        return created;

    }

按预期获取请求 return 数据:

    [HttpGet]
    [Route("{id}")]
    public IHttpActionResult GetApplication(string id)
    {
        var application = _applicationResource.GetById(id);
        return Ok(application);
    }

那是因为您没有等待异步方法:

这个:

var doc = _applicationResource.Save(data);

需要:

var doc = await _applicationResource.Save(data);

您的方法应如下所示:

[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateNewApplication(dynamic data)
{
    if (data == null)
    {
        return BadRequest("data was empty");
    }

    try
    {
        var doc = await _applicationResource.Save(data);
        return Ok(doc.Id); //code hits this point and 'returns'
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}