C# 仅在当前线程(.NET)中检查服务器/SSL证书
我有一个多线程应用程序,它连接到许多URL,并且只需要在某些线程上检查SSL证书 我知道我可以使用C# 仅在当前线程(.NET)中检查服务器/SSL证书,c#,.net,httpwebrequest,ssl-certificate,webclient,C#,.net,Httpwebrequest,Ssl Certificate,Webclient,我有一个多线程应用程序,它连接到许多URL,并且只需要在某些线程上检查SSL证书 我知道我可以使用ServicePointManager.ServerCertificateValidationCallback,但它可以在异步模式下同时跨所有线程工作 我需要在连接到URL的函数的同步执行中的当前线程中进行检查 有什么想法吗?您可以定义请求和证书功能之间的映射,如下所示: // delegate definition for cert checking function private delega
ServicePointManager.ServerCertificateValidationCallback
,但它可以在异步模式下同时跨所有线程工作
我需要在连接到URL的函数的同步执行中的当前线程中进行检查
有什么想法吗?您可以定义请求和证书功能之间的映射,如下所示:
// delegate definition for cert checking function
private delegate bool CertFunc(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);
// mapping between outbound requests and cert checking functions
private static readonly ConcurrentDictionary<HttpWebRequest, CertFunc> _certFuncMap = new ConcurrentDictionary<HttpWebRequest, CertFunc>();
// global cert callback
private static bool ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// call back into the cert checking function that is associated with this request
var httpWebRequest = (HttpWebRequest)sender;
CertFunc certFunc = _certFuncMap[httpWebRequest];
return certFunc(certificate, chain, sslPolicyErrors);
}
// register the global cert callback
ServicePointManager.ServerCertificateValidationCallback += ServerCertificateValidationCallback;
// create the request object
var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
// cert checking function
CertFunc certFunc = (certificate, chain, sslPolicyErrors) =>
{
// perform cert logic here
return true;
};
_certFuncMap[httpWebRequest] = certFunc;
using (var webResponse = httpWebRequest.GetResponse())
{
// process the response...
}
// clean up the mapping
_certFuncMap.TryRemove(httpWebRequest, out certFunc);