WebAPI:在业务逻辑中使用异步方法

时间:2017-02-27 09:49:56

标签: c# asp.net-web-api async-await

目的是让控制器在我的自定义服务中使用异步方法。

控制器:

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

服务:

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

但我遇到的问题是,在服务实际处理完数据之前,控制器的操作会返回空结果。

您能否建议如何正确实施?

2 个答案:

答案 0 :(得分:2)

您的代码没问题,控制器似乎在GetDataObjects返回值之前没有返回值。

以下情况除外:

  1. MakeEntities使用了一些异步操作,你不在MakeEntities中等待它。所以MakeEntities返回任务。

  2. 代码运行时异常会增加。确保GetDataObjectsMakeEntities代码正常运行。

答案 1 :(得分:0)

目的是让控制器在我的自定义服务中使用异步方法。

控制器:

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

服务:

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