1
votes

I have created a documentDB on Azure and can successfully create and get documents.

However, whilst documents are successfully created in the DB, I am not able to use the response from CreateDocumentAsync. The code immediately returns to the calling method on the controller. So the debug line is never reached.

Moreover I am setting the id to a guid, but the Document that is returned to the controller has an Id of 1.

Controller

    [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);
        }
    }

Resource

  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;

    }

Get requests return data as expected:

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

1 Answers

3
votes

That's because you're not awaiting an asynchronous method:

This:

var doc = _applicationResource.Save(data);

Needs to be:

var doc = await _applicationResource.Save(data);

Your method should look as follows:

[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);
    }
}