Error creating HttpClient helper method

I have a working asynchronous task calling 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 highlight the creation of an HttpClient object so that 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 is functionally identical to me, the latter throws an error AggregateExceptionwith an internal exception

Unable to access the remote object. Object Name: "System.Net.Http.HttpClient".

Perhaps there is some kind of asynchronous subtlety that I do not understand?

+4
source share
1 answer

using GetClient. using , " ", " ", return client;.

using ( GetResult).

asnyc IDisposable.

+7

Source: https://habr.com/ru/post/1627481/


All Articles