我在.NET Core中制作了一个小型控制台应用程序,用于在验证过程中使用.pfx / .p12证书进行REST / Http请求。当我向其提供带有正确密码的正确证书时,该应用程序正常运行。但是只要我
,它就会崩溃更具体地说,我得到以下异常:
System.Net.Http.HttpRequestException:“无法建立SSL连接,请参阅内部异常。”
AuthenticationException:身份验证失败,请参阅内部异常。
Win32Exception:收到的消息意外或格式错误
我宁愿获得与无效调用相对应的HTTP响应,这似乎是使用SOAPUI时得到的。
我使用以下方法制作HttpClientHandler:
private static HttpClientHandler GetClientHandler(string certificate, string password)
{
X509Certificate2 certPfx;
try {
certPfx = new X509Certificate2(certificate, password);
}
catch(CryptographicException e) {
Console.WriteLine($ "Error occured while trying to load certificate: {e.Message}");
return null;
}
var clientHandler = new HttpClientHandler();
clientHandler.SslProtocols = SslProtocols.Tls12;
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
clientHandler.ClientCertificates.Add(certPfx);
clientHandler.ServerCertificateCustomValidationCallback += (HttpRequestMessage req, X509Certificate2 cert2, X509Chain chain, SslPolicyErrors err) = >true;
return clientHandler;
}
然后我使用以下代码进行POST请求:
using(var client = handler != null ? new HttpClient(handler, true) : new HttpClient())
{
AddHeaders(client, headers);
var httpContent = new StringContent(request.ToString(), Encoding.UTF8, "application/xml");
Console.WriteLine("Response from service:");
Console.WriteLine("----------------------");
var response = await client.PostAsync(endpoint, httpContent);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.WriteLine("----------------------");
Console.WriteLine("----------------------");
}