Forcing ASP.NET WebAPI client to send a client certificate even when no CA match

余生颓废 提交于 2019-12-03 06:22:57

I had the same issue and same no luck. Also observed a strange behaviour, when WebRequesthandler sometimes did send the certificate, depending on the thread / AppPool credentials.

I have managed to sort this out by replacing HttpClient with RestClient. RestClient is OpenSource and available via nuget.

RestSharp page

The API is very similar and does the required magic without moaning about the certificate:

        var restClient = new RestClient($"{serviceBaseUrl}{requestUrl}");
        X509Certificate certificate = GetCertificateFromSomewhere();
        restClient.ClientCertificates = new X509CertificateCollection { certificate };
        var request = new RestRequest(Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddParameter(new Parameter()
        {
            Type = ParameterType.RequestBody,
            Name = "Body",
            ContentType = "application/json",
            Value = "{your_json_body}"
        });

        IRestResponse<T> response = client.Execute<T>(request);
        if (response.ErrorException != null)
        {
            throw new Exception(response.Content, response.ErrorException);
        }
        return response.Data;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!