I\'m getting this exception using http client in my api.
An unhandled exception has occurred while executing the request. System.InvalidOperationExc
Singletons are the correct approach. Using scoped or transient will prevent connection pooling and lead to perf degradations and port exhaustion.
If you have consistent defaults then those can be initialized once when the service is registered:
var client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
services.AddSingleton(client);
...
var incoming = new Uri(uri, UriKind.Relative); // Don't let the user specify absolute.
var response = await _client.GetAsync(incoming);
If you don't have consistent defaults then BaseAddress and DefaultRequestHeaders should not be used. Create a new HttpRequestMessage instead:
var incoming = new Uri(uri, UriKind.Relative); // Don't let the user specify absolute urls.
var outgoing = new Uri(new Uri("http://example.com/"), incoming);
var request = new HttpRequestMessage(HttpMethod.Get, outgoing);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _client.SendAsync(request);