Search code examples
c#restasp.net-coredotnet-httpclient

ASP.NET Core 2.x - HttpClient api returns error 'Object reference not set to an instance of an object'


I query a public API (https://api.bitfinex.com/v1/pubticker/ethusd) by sending httpClient message request, but I don't know why the result returns as a null object error, even though the REST API itself works just fine. Where was I wrong?

private readonly HttpClient _httpClient;
private const string apiUri = "https://api.bitfinex.com/v1/pubticker/ethusd";

public DataController(
  HttpClient httpClient
)
{
  httpClient = _httpClient;
}

[HttpGet("ticker")]
[ProducesResponseType(typeof(Ticker), 200)]
public async Task<IActionResult> GetTicker()
{
  HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUri);
  requestMessage.Headers.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json")
  );

  var response = await _httpClient.SendAsync(requestMessage);
  
  return Ok(response);
}

Solution

  • The problem is attempting to serialize the response from HttpClient. That is incorrect, and will cause all sorts of issues, because you've got streams and such involved. What you should do instead is read the content into an object and then return that:

    using (var response = await _httpClient.SendAsync(requestMessage))
    {
        var content = await response.Content.ReadAsAsync<SomeClass>();
        return Ok(content);
    }
    

    Alternatively, if you're not using a class that you can map to, and don't want to create one, you can manually deserialize the response content using JSON.NET directly:

    using (var response = await _httpClient.SendAsync(requestMessage))
    {
        var content = await response.Content.ReadAsStringAsync();
        var model = JsonConvert.DeserializeObject(content);
        return Ok(model);
    }