我正在尝试使用.NET Core 2向第三方端点发出Web请求。端点需要使用客户端证书以及用户名和密码进行身份验证。到目前为止,我尝试的所有内容都会导致403(禁止)错误。到目前为止,我已尝试过以下内容:
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2(certificate));
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
我也试过了:
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(url);
var cert = new X509Certificate2(certificate);
request.ClientCertificates.Add(cert);
request.Credentials = new NetworkCredential(username, password);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
到目前为止,我只是想做一个GET但最终我需要做一个POST。
如上所述,两者都会产生403.如果我针对.NET Framework运行第二个示例,它就可以正常工作。此外,如果我有Fiddler运行,那么我会返回OK状态,而不是403.
对于我正在做错的任何想法阻止.NET Core成功连接到端点?
答案 0 :(得分:1)
我最终将代码切换到下面的代码并完成了诀窍。我将ClientCertificateOption设置为Automatic,我手动删除了指定证书。
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.SslProtocols = SslProtocols.Tls12;
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}