Reputation: 2574
I want to share an instance of HttpClient
between different requests and it seems fortunately this class is safe to be used cuncurrently.
But I need to set HttpMessageHandler
for each individual request since they may have different ClientCertificates. Apparently this can only be done via constructor and not available after initialization!
Any idea how to set this property after initialization? or a workaround?
Upvotes: 5
Views: 6142
Reputation: 3738
Not exactly setting it after instantiation, but would this approach work in your case?
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
public abstract class MyHttpClient : HttpClient
{
protected MyHttpClient() : base(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })
{
DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
DefaultRequestHeaders.AcceptCharset.Add(StringWithQualityHeaderValue.Parse("UTF-8"));
DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip"));
}
}
Upvotes: 1
Reputation: 15221
You might want to use WebRequestHandler as a handler added to HttpClient constructor, keep its reference and then change certificates on per request basis. this link might help: https://blogs.msdn.microsoft.com/henrikn/2012/08/07/httpclient-httpclienthandler-and-webrequesthandler-explained/
Upvotes: 3