HttpClient - This instance has already started

前端 未结 2 1524
予麋鹿
予麋鹿 2020-12-08 20:11

I\'m getting this exception using http client in my api.

An unhandled exception has occurred while executing the request. System.InvalidOperationExc

2条回答
  •  猫巷女王i
    2020-12-08 20:34

    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);
    

提交回复
热议问题