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

use*_*108 6 c# ssl

我需要将数据发送到需要证书授权的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我搜索了谷歌,发现了一个"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();
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,服务器响应403禁止...如何检查授权是否与证书一起使用?

更新2:

似乎这个问题的答案在于调试: 在此输入图像描述

我测试了密码并使用错误的证书密码发生异常.所以我不确定服务器是否接受证书但是服务器路径已经死或服务器不接受证书.

更新3:

查看显示更多信息的响应对象,但如果证书导致错误则不显示. 在此输入图像描述

但内容中有一个例外? 在此输入图像描述

更新4:

不幸的是,服务器从未收到过证书......

最后更新

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

Pet*_*ons 12

您应该使用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))
{
    ....
}
Run Code Online (Sandbox Code Playgroud)

有关更多背景信息,另请参阅此链接