我需要向需要证书授权的Web API发送数据。但是我不知道如何将证书添加到.Net 4.5中的处理程序中。以下是代码:
// Import the certificate
X509Certificate2Collection certificates = new X509Certificate2Collection();
certificates.Import(pathToCertificate, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
using (var handler = new HttpClientHandler() { })
{
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Build the JSON
string json = JsonConvert.SerializeObject(userData, Formatting.Indented);
Console.WriteLine(json);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var processResult = await client.PostAsync(uriToServer, httpContent);
var responseBody = processResult.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBody);
//return JsonConvert.DeserializeObject<string>(responseBody);
}
}
我在谷歌上搜索并找到了一个“HttpClientHandler.ClientCertificates.Add”,但那是针对 .Net Core 而不是 4.5。
这是否适用于 HttpClient,还是我必须使用 HttpWebRequest 类?
更新:
相关的答案来自“Peter Bons”(再次感谢),由于使用仅为 try-finally,因此我将代码更改为:
// Create an WebRequestHandler instance
var handler = new WebRequestHandler();
// Add the certificate
var certFile = Path.Combine(pathToWorkingDirectory, "SERVER.PFX");
handler.ClientCertificates.Add(new X509Certificate2(certFile, "password"));
var client = new HttpClient(handler);
try
{
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
//var processResult = await client.GetAsync("https://server/login");
var processResult = await client.PostAsync("https://server/p/m", httpContent);
var responseBody = processResult.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine($"ERROR: {e}");
}
finally
{
client.Dispose();
}
很不幸,服务器返回了403禁止访问的错误信息...我该如何检查证书授权是否有效?更新2:看起来这个问题的答案在于调试:
![enter image description here](https://istack.dev59.com/xuA3D.webp)
![enter image description here](https://istack.dev59.com/eluxU.webp)
![enter image description here](https://istack.dev59.com/7tPfs.webp)
很遗憾,服务器从未收到证书... 最后更新 问题出在我从系统管理员那里获取的证书。代码可以运行。问题解决 :)