Search code examples
c#.net-coredotnet-httpclientpollyhttpclientfactory

HttpClientFactory throws an error on client setup


How is it possible that I get this error message in the setup of a client when I use HttpClientFactory? Who is already using this client? I've been trying both like this as a named client and also by specifying the <Interface,Class> so it can add it as a transient - same error.

services.AddHttpClient("xxx", async client =>
{
  var tokenData = await jwtTokenProvider.GetTokenAsync(appSettingsSectionIdentity);
  if (tokenData is null || !tokenData.IsValid)
    throw new TechnicalErrorException("Can't get a token xxx");
  client.CancelPendingRequests();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "xx");
  client.BaseAddress = new Uri(baseAddress);
}).AddPolicyHandler(PollyPolicys.xxx());
  • I've also tried to comment out that polly-policy, same behaviour
  • And I also added that CancelPendingRequests() but no luck
  • The TokenProvider has its own httpClient

client.BaseAddress is null here, and the baseaddress is set outside of this lambda.

The error message:

"This instance has already started one or more requests. Properties can only be modified before sending the first request"

enter image description here

And I simply request this client by:

var httpClient = _httpClientFactory.CreateClient("xxx");

Solution

  • Just to capture here the essence of our discussion in the chat:

    • The GetToken was also using the HttpClient
    • Changing the order of the BaseAddress assignment and Header assignment helped
    • The configureClient should be a synchronous delegate not an async one, because that is not supported by any of the AddHttpClient overload

    The suggested modification is the following:

    services.AddHttpClient();
    
    var tokenData = await jwtTokenProvider.GetTokenAsync(appSettingsSectionIdentity);
    if (tokenData is null || !tokenData.IsValid)
        throw new TechnicalErrorException("Can't get a token xxx");
    var token = await GetToken(tokenData, apiKey); //I assumed that this async as well
    
    services.AddHttpClient("xxx", client =>
    {
      client.BaseAddress = new Uri(baseAddress);
      client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
      
    }).AddPolicyHandler(PollyPolicys.xxx());