gpt4 book ai didi

C#,如何将证书添加到 HttpClientHandler?

转载 作者:太空狗 更新时间:2023-10-29 21:04:00 26 4
gpt4 key购买 nike

我需要将数据发送到需要证书授权的网络 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”的给定答案相关(再次感谢)并且由于使用只是尝试 - 最后我将代码更改为:

// 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 forbidden...如何检查授权是否与证书一起使用?

更新 2:

这个问题的答案似乎在于调试: enter image description here

我测试了密码,但证书密码错误,出现异常。所以我不确定服务器是否正在接受证书,但服务器路径已失效或服务器未接受证书。

更新 3:

查看显示更多信息的响应对象,但如果证书导致错误则不会。 enter image description here

但是内容里面有Exception? enter image description here

更新 4:

很遗憾,服务器从未收到证书...

最后更新

问题是我从系统管理员那里获得的证书。代码有效。问题解决了。 :)

最佳答案

您应该像本例中那样使用 WebRequestHandler 类:

var handler = new WebRequestHandler();

var certFile = Path.Combine(@"d:\temp\", "cert.pfx");
handler.ClientCertificates.Add(new X509Certificate2(certFile, "password"));

using (var client = new HttpClient(handler))
{
....
}

另见 this link了解更多背景信息

关于C#,如何将证书添加到 HttpClientHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com