1

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

4
  • Your method should be marked async so you can do var response = await client.GetAsync(...) instead of firing an async task and then immediately blocking your thread to wait for the result. Note that .Wait() is redundant since .Result will always have to wait. As for your error, responseTask is the Task but you're treating it as its result. Commented Jun 23, 2022 at 12:13
  • Also if the method was async you could await response.Content.ReadAsAsync<JArray>() without needing to go Task.Run(...).Result Commented Jun 23, 2022 at 12:16
  • "responseTask" is of type "Task<HttpResponseMessage>" and that does not have a "Headers" property of course. You would need to write "string error = responseTask.Result.Headers.TryGetValue(....)" Commented Jun 23, 2022 at 12:38
  • The extension below helps you to get HttpClient in the form of a curl script. Nuget Package Commented Nov 30, 2023 at 21:26

1 Answer 1

1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.