Postman可正常运行的HttpWebRequest请求在代码中报错排查
问题描述
用Postman发送无请求体、仅通过用户名密码Basic认证的Token请求时正常,但用C#代码实现时返回错误:
The request was aborted: Could not create SSL/TLS secure channel.
代码如下:
string responsedata = string.Empty; String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToken); request.Method = "POST"; request.Headers.Add("Authorization", "Basic " + encoded); request.PreAuthenticate = true; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { responsedata = reader.ReadToEnd(); }
解决方案
这个错误核心原因是C#程序默认使用的TLS版本与服务器要求不匹配,Postman会自动适配支持的TLS版本,而HttpWebRequest默认可能启用了过时的TLS 1.0/1.1,现在多数服务器仅支持TLS 1.2及以上版本。
强制指定TLS版本:在创建请求前添加代码,强制使用TLS 1.2或更高版本:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;注:若使用.NET Framework 4.5及以下版本,需先升级框架,或手动注册TLS 1.2支持。
处理证书信任问题:若服务器使用自签名证书,Postman默认跳过验证,但C#代码会严格校验。测试环境可临时添加回调跳过检查(生产环境禁用):
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;补充必要请求头:Postman会自动添加部分默认头(如
Content-Type),部分服务器即便无请求体也要求该头,可尝试添加:request.ContentType = "application/x-www-form-urlencoded"; // 或服务器支持的其他类型
内容的提问来源于stack exchange,提问作者Kinyanjui Kamau
相关产品推荐
相关产品推荐

