यहां अधिकांश उत्तर विशिष्ट पैटर्न का उपयोग करने का सुझाव देते हैं:
using (var httpClient = new HttpClient())
{
// do something
}
आईडीसॉफ़्टरी इंटरफ़ेस के कारण। कृपया नहीं!
Microsoft आपको बताता है:
और यहाँ आप एक विस्तृत विश्लेषण पा सकते हैं कि पर्दे के पीछे क्या चल रहा है:
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
आपके SSL प्रश्न के बारे में और https://docs.microsoft.com/en-us/azure/ RGBecture/antipatterns/improper-instantiation/#how-to-fix-the-problem पर आधारित
यहाँ आपका पैटर्न है:
class HttpInterface
{
// https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/#how-to-fix-the-problem
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient#remarks
private static readonly HttpClient client;
// static initialize
static HttpInterface()
{
// choose one of these depending on your framework
// HttpClientHandler is an HttpMessageHandler with a common set of properties
var handler = new HttpClientHandler();
{
ServerCertificateCustomValidationCallback = delegate { return true; },
};
// derives from HttpClientHandler but adds properties that generally only are available on full .NET
var handler = new WebRequestHandler()
{
ServerCertificateValidationCallback = delegate { return true; },
ServerCertificateCustomValidationCallback = delegate { return true; },
};
client = new HttpClient(handler);
}
.....
// in your code use the static client to do your stuff
var jsonEncoded = new StringContent(someJsonString, Encoding.UTF8, "application/json");
// here in sync
using (HttpResponseMessage resultMsg = client.PostAsync(someRequestUrl, jsonEncoded).Result)
{
using (HttpContent respContent = resultMsg.Content)
{
return respContent.ReadAsStringAsync().Result;
}
}
}