Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue creating HttpClient helper method

I have a functioning async Task that calls a web service:

private async Task GetResult()
{
   using (var client = new HttpClient())
   {
      client.BaseAddress = new Uri(_baseAddress);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));
      client.DefaultRequestHeaders.Add("Username", _username);
      client.DefaultRequestHeaders.Add("Action", "GET");
      /* etc */
      var response = await client.GetAsync(client.BaseAddress);
   }
}

I would like to separate out the creation of the HttpClient object so it can be parameterized and reused:

private async Task GetResult()
{
   using (var client = GetClient(_baseAddress, _username))
   {
      var response = await client.GetAsync(client.BaseAddress);
   }
}
private static HttpClient GetClient(string Address, string Username)
{
   using (var client = new HttpClient())
   {
      client.BaseAddress = new Uri(Address);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(
         new MediaTypeWithQualityHeaderValue("application/json"));
      client.DefaultRequestHeaders.Add("Username", Username);
      client.DefaultRequestHeaders.Add("Action", "GET");
      /* etc */
      return client;
   }
}

While this appears functionally identical to me, the latter throws an AggregateException error with inner exception

Cannot Access a disposed object. Object name: 'System.Net.Http.HttpClient'.

Perhaps there is some async subtlety that I don't understand?

like image 831
Matt Avatar asked Feb 08 '23 19:02

Matt


1 Answers

Get rid of the using inside of GetClient. You only use using for things that remain "in your ownership", you are "giving up ownership to the caller" when you return client;.

It is now the caller's resposability to use a using statement (which you do already correctly do in GetResult).

This has nothing to do with asnyc and is simply standard IDisposable behavior.

like image 165
Scott Chamberlain Avatar answered Feb 16 '23 03:02

Scott Chamberlain