Search code examples
httpasp.net-web-apiasync-awaitdotnet-httpclient

Call GetAsync from a WebAPI controller


I am trying to return a HTTP result from a controller method in ASP.NET WebAPI. I am calling a GetAsync method, so I need to use async-await and return a Task<T>.

This is the controller method, of course, simplified for illustrative purposes:

[HttpGet]
public async Task<string> MyMethod()
{   
    var url = @"http://localhost/whatever";
    return await HttpGet<string>(url);  
}

And the HTTP call method, with parameters and Authorization abstracted away:

private async Task<T> HttpGet<T>(string url)
{
    var _httpClient = new HttpClient();

    var response = await _httpClient.GetAsync(url);
    if (response.IsSuccessStatusCode)
        return await response.Content.ReadAsAsync<T>();

    throw new Exception($"{response.StatusCode} - {response.RequestMessage}");              
}

I get an error below after return await in HttpGet method:

"Message": "An error has occurred.",

"ExceptionMessage": "Unexpected character encountered while parsing value: [. Path '', line 1, position 1.",

"ExceptionType": "Newtonsoft.Json.JsonReaderException"

Any advice?


Solution

  • The problem was in the return type of the HTTP call. It was a list of objects, while I was telling ReadAsAsync<T> to expect a string.

    This solved it:

    [HttpGet]
    public async Task<List<MyClass>> MyMethod()
    {   
        var url = @"http://localhost/whatever";
        return await HttpGet<List<MyClass>>(url);  
    }