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

时间:2017-10-30 16:26:58

标签: 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);
    }
}

我搜索了谷歌并找到了一个&#34; HttpClientHandler.ClientCertificates.Add&#34;但那是.Net Core而不是4.5。

这是否可以使用HttpClient或我是否必须使用HttpWebRequest类?

更新

与Peter Bons&#34; (再次感谢)因为使用只是尝试 - 最后我将代码更改为:

// 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

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

更新3:

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

但是内容中有一个Exception? enter image description here

更新4:

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

最后更新

问题是我从sysadmin获得的证书。代码有效。问题解决了。 :)

1 个答案:

答案 0 :(得分:10)

您应该使用此示例中的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