Calling external HTTP service using HttpClient from a Web API Action

Aha, I needed to do the following (return a Task rather then void):

 // GET api/values
    public async Task<IEnumerable<string>> Get()
    {
        var result = await GetExternalResponse();

        return new string[] { result, "value2" };
    }

    private async Task<string> GetExternalResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsStringAsync();
        return result;
    }

Also I hadn’t realised I could mark the Get() operation as async which is what allowed me to await the external call.

Thanks to Stephen Cleary for his blog post Async and Await which pointed me in the right direction.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)