如何在 C# 中调用需要证书的 Web 服务?

How to invoke a Web Service which requires a certificate in C#?

我需要与具有 .asmx 网络服务的第三方通信。此 Web 服务使用 https。我有所需的证书 (.pfx)。

第一次尝试使用 Visual Studio 中的 Add Service Reference 添加此服务时,出现错误。我通过将证书导入 Personal 商店来解决这个错误。在我这样做之后,我尝试再次添加服务参考并且它有效。所以现在我可以创建一个 Web 服务实例。不错

但现在我想调用该服务。当我这样做时,我得到了这个错误:

302 Notification: Digital Certificate Missing

那么我怎样才能告诉我的服务使用正确的证书呢?

尝试在获取请求流之前添加:

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
request.ProtocolVersion = HttpVersion.Version10;
request.ClientCertificates.Add(new X509Certificate2("YourPfxFile(full path).pfx", "password for your pfx file");

根据您的安全要求和环境,您可能需要使用不同的 SecurityProrocolType 值。

我终于设法解决了我的问题,如下所示:

var service = new Service1SoapClient();
service.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.TrustedPublisher, X509FindType.FindByIssuerName, "name_of_issuer");
((BasicHttpBinding)service.Endpoint.Binding).Security.Mode = BasicHttpSecurityMode.Transport;
((BasicHttpBinding)service.Endpoint.Binding).Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

请使用Certificate.pfx并使用密码安装。

我在请求 Web 服务时也遇到了“请求被中止:无法创建 SSL/TLS 安全通道”的问题。 修复了以下代码的问题,希望这对某人有所帮助并节省时间。

 HttpWebRequest web_request = (HttpWebRequest)WebRequest.Create("https://yourservices/test.asmx");
        web_request.ContentType = "text/xml;charset=\"utf-8\"";

        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        web_request.ProtocolVersion = HttpVersion.Version10;

        X509Certificate2Collection certificates = new X509Certificate2Collection();
        certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

        web_request.ClientCertificates = certificates;
        web_request.Accept = "text/xml";
        web_request.Method = "POST";

        using (Stream stm = web_request.GetRequestStream())
        {
            using (StreamWriter stmw = new StreamWriter(stm))
            {
                stmw.Write(soap);
            }
        }

        WebResponse web_response = null;
        StreamReader reader = null;

        try
        {
            web_response = web_request.GetResponse();
            Stream responseStream = web_response.GetResponseStream();
            XmlDocument xml = new XmlDocument();

            reader = new StreamReader(responseStream);
            xml.LoadXml(reader.ReadToEnd());
        }
        catch (Exception webExp) {
            string exMessage = webExp.Message;
        }