Vasanth R
Vasanth R

Reputation: 212

How to read header values with HttpClient in .net core

This is the code i'm using

using (var client = new HttpClient())
{
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));            

  var url = $"...some url";            

  var requestUri = new Uri(url);

  var responseTask = client.GetAsync(requestUri);
  responseTask.Wait();
           

  var result = responseTask.Result;
  if (result.IsSuccessStatusCode)
  {
    var reportResults = Task.Run(async() => await result.Content.ReadAsAsync<JArray>()).Result;
    return reportResults;
  }
}

Here if i try to access header like this

string error = responseTask.Headers.TryGetValue("X-TotalResults").FirstOrDefault();

I'm getting error

Task<HttpResponseMessage> does not contain a 
definition for Headers and no accessible extension method Headers

So How i can read the header .. thanks in advance

Upvotes: 1

Views: 1398

Answers (1)

Charlieface
Charlieface

Reputation: 71544

You have a Task<HttpResponseMessage> rather than a HttpResponseMessage.

Instead of using .Result, which is dangerous for many reasons, convert your code to use async properly.

static HttpClient client = new HttpClient();

private async JArray GetReportResults()
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", HttpContext.Session.GetString("JwtToken"));            

    var url = $"...some url";            

    using (var response = await client.GetAsync(url))
    {           
        result.EnsureSuccessStatusCode()
        var reportResults = await result.Content.ReadAsAsync<JArray>();
        return reportResults;
    }
}

Upvotes: 1

Related Questions