带证书的WCF WebService API POST调用失败,测试程序正常
WCF WebService调用外部API时证书发送失败(本地WinForms测试正常)
环境信息
- WCF服务:.NET Framework 4.8.1,部署在IIS独立应用程序池,以专用服务用户身份运行
- 服务器:Windows Server 2019,已安装.NET Framework 4.8
- 测试程序:WinForms(.NET Framework 4.8),以当前Windows用户身份启动
核心代码
类级常量
private static readonly UTF8Encoding _utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
API调用方法
HttpWebRequest webRequest = WebRequest.CreateHttp(uri); webRequest.Method = "POST"; webRequest.ContentType = "application/json"; webRequest.Headers.Add("Cache-Control", "no-cache"); webRequest.PreAuthenticate = true; string _certificateThumbprint = "XXX"; bool _validCertificateOnly = true; X509Store store = new X509Store(StoreLocation.LocalMachine); //store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); X509Certificate2Collection certCollection = store.Certificates; X509Certificate2 certificate = certCollection.Find(X509FindType.FindByThumbprint, _certificateThumbprint, validOnly: _validCertificateOnly).OfType<X509Certificate2>().FirstOrDefault(); if (certificate != null && (!_validCertificateOnly || certificate.Verify())) { webRequest.ClientCertificates.Add(certificate); } string _authUsername = "YYY"; string _authPassword = "ZZZ"; string creds = Convert.ToBase64String(_utf8.GetBytes(_authUsername + ":" + _authPassword)); webRequest.Headers["Authorization"] = $"Basic {creds}"; string jsonString = "Some JSON data..."; byte[] Content = _utf8.GetBytes(jsonString); webRequest.ContentLength = Content.Length; // 错误触发位置 using (Stream RequestStream = webRequest.GetRequestStream()) { RequestStream.Write(Content, 0, Content.Length); }
Web.config配置
<system.web> <compilation debug="true" targetFramework="4.6" /> <httpRuntime targetFramework="4.5.2" /> </system.web>
报错情况
- 使用上述配置时:
System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
- 将web.config中两处框架版本改为4.8后:
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
额外信息
对方服务端反馈WCF调用时未发送客户端证书,但WinForms测试程序调用完全正常。
内容的提问来源于stack exchange,提问作者BummzuaBua
相关产品推荐
相关产品推荐

