我已经在Azure上创建了documentDB,可以成功创建和获取文档。
但是,虽然在数据库中成功创建了文档,但是我无法使用CreateDocumentAsync的响应。该代码立即返回到控制器上的调用方法。因此,调试行永远不会到达。
此外,我将id设置为guid,但是返回到控制器的Document的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;
}
获取请求按预期返回数据:
[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);
}
}
关于c# - 无法使用Async DocumentDB操作CreateDocumentAsync的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30161380/