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());
CancelPendingRequests()
but no luckclient.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"
And I simply request this client by:
var httpClient = _httpClientFactory.CreateClient("xxx");
Just to capture here the essence of our discussion in the chat:
GetToken
was also using the HttpClient
BaseAddress
assignment and Header assignment helpedconfigureClient
should be a synchronous delegate not an async one, because that is not supported by any of the AddHttpClient
overloadThe 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());