我认为您有多个证书或需要多个证书并需要附加它们。您可以向 X509CertificateCollection 添加尽可能多的证书。其中之一必须与 https 服务器证书匹配,否则您无法调用 Web 服务。
try
{
X509Certificate2 clientCert = GetClientCertificate("cert1");
X509Certificate2 clientCert = GetClientCertificate("cert2");
X509Certificate2 clientCert = GetClientCertificate("cert3");
WebRequestHandler requestHandler = new WebRequestHandler();
requestHandler.ClientCertificates.Add(clientCert1);
requestHandler.ClientCertificates.Add(clientCert2);
requestHandler.ClientCertificates.Add(clientCert3); HttpClient client = new HttpClient(requestHandler) { BaseAddress = new Uri(" http://localhost:3020/ ") };
HttpResponseMessage response = client.GetAsync("customers").Result;
response.EnsureSuccessStatusCode();
string responseContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseContent);
}
catch (Exception ex)
{
Console.WriteLine("Exception while executing the test code: {0}", ex.Message);
}
然后调用这个请求。
private static X509Certificate2 GetClientCertificate( string probablerightcert)
{
X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
userCaStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, probablerightcert, true);
X509Certificate2 clientCertificate = null;
if (findResult.Count == 1)
{
clientCertificate = findResult[0];
}
else
{
throw new Exception("Unable to locate the correct client certificate.");
}
return clientCertificate;
}
catch
{
throw;
}
finally
{
userCaStore.Close();
}
}