Skip to main content
 首页 » 编程设计

c#之无法为 SSL/TLS C# Web 服务客户端建立安全通道

2024年01月29日27grandyang

我有一个 WPF 应用程序,它在同一个基本 URL 上调用 4 个 Web 服务(用 Java 编写),在我安装谷歌浏览器之前它一直运行良好。我安装了 chrome,但出现了这个错误:

Could not establish secure channel for SSL/TLS C# Web service

我没有再写代码。发生这种情况是因为我安装了 chrome 然后我删除了 chrome 但没有用,我尝试了系统还原,卸载了 eset smart security 并清理了所有 windows(8.1 单一语言)证书。那我怎么弄明白呢?这是我的网络服务调用者

public string call(string url, string json) 
{ 
    try 
    { 
        var webrequest = (HttpWebRequest)WebRequest.Create(url); 
        var key = JsonConvert.SerializeObject(LoginService.SessionData.SessionKey); 
        UTF8Encoding uTF8Encoding = new UTF8Encoding(); 
        byte[] requestBytes = uTF8Encoding.GetBytes(json); 
        WebClient client = new WebClient(); 
 
        webrequest.Method = "POST"; 
        webrequest.Headers.Add("SESSION_KEY", LoginService.SessionData.SessionKey); 
        webrequest.ContentType = "application/json"; 
        webrequest.ContentLength = requestBytes.LongLength; 
        Stream requestStream = webrequest.GetRequestStream();//here the exception 
        requestStream.Write(requestBytes, 0, requestBytes.Length); 
 
        using (var response = webrequest.GetResponse()) 
        using (var reader = new StreamReader(response.GetResponseStream())) 
        { 
            var responseBuf = reader.ReadToEnd(); 
            String responseJson = Convert.ToString(responseBuf); 
            return responseJson; 
        } 
    } 
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.Message); 
    } 
    return null; 
} 

请您参考如下方法:

根据我的观察,过去几个月有大量服务正在关闭 SSL 和/或旧版 TLS 以缓解它们固有的安全问题。

在 AppDomain 中的任何地方,您都可以像这样强制连接使用 TLS 1.2:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

如果您还需要支持旧版本,您也可以OR将多个版本组合在一起:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12