user1820686
user1820686

Reputation: 2117

WebAPI: using async methods in business logic

The aim is to make controller that uses async method in my custom service.

Controller:

[Route("api/data/summary")]
[HttpGet]
public async Task<IHttpActionResult> Get()
{
    var result = await DataService.GetDataObjects();
    return Ok(result);
}

Service:

public static async Task<IEnumerable<DataObject>> GetDataObjects()
{
    var apiKey = "some-api-key";
    var path = "path-to-external-service";
    using (var client = new HttpClient())
    {
        var dataToProcess = // some data object

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.BaseAddress = new Uri(path);

        HttpResponseMessage response = await client.PostAsJsonAsync("", dataToProcess);
        var content = await response.Content.ReadAsStringAsync();

        var result = MakeEntities(content); // some logic

        return result;
    }
}

But I came across with the problem that controller's action returns empty result before service actually finished processing data.

Could you please advice how to implement it correctly?

Upvotes: 0

Views: 982

Answers (2)

Pavel
Pavel

Reputation: 656

Your code is OK and controller doesn't seem to return a value before GetDataObjects returns value.

Except for the situations below:

  1. MakeEntities uses some asynchronous operation and you don't await it inside MakeEntities. So MakeEntities return task.

  2. Exception rises while your code is running. Make sure GetDataObjects and MakeEntities code works fine.

Upvotes: 2

Aakash Prajapati
Aakash Prajapati

Reputation: 41

The aim is to make controller that uses async method in my custom service.

Controller:

[HttpGet]
[Route("api/data/summary")]
public async Task<IHttpActionResult> Get()
{
    var result = await DataService.GetDataObjects().ConfigureAwait(false);
    return Ok(result);
}

Service:

public static async Task<ResponseEntity> GetDataObjects()
{
    ResponseEntity response = new ResponseEntity();
    var apiKey = "some-api-key";
    var path = "path-to-external-service";
    using (var client = new HttpClient())
    {
        var dataToProcess = // some data object    
        client.BaseAddress = new Uri(path);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
        HttpResponseMessage response = await client.PostAsJsonAsync("", dataToProcess).ConfigureAwait(false);
        string responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);    
        var result = JsonConvert.DeserializeObject<ResponseEntity>(responseString);

        return response;
    }
}

Upvotes: 0

Related Questions