Skip to main content
 首页 » 编程设计

c#之将 HttpClient 和 HttpWebRequest 用于 Https TLS1.2

2024年02月25日34mayingbao

在控制台应用程序中,尝试访问使用 TLS 1.2 配置的“https”端点。

在 C# 中 使用 HttpClient 时,我从端点获得了成功响应

       HttpClient httpClient = new HttpClient(); 
 
        //specify to use TLS 1.2 as default connection 
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 
 
        httpClient.BaseAddress = new Uri("HTTPSENDPOINT"); 
        httpClient.DefaultRequestHeaders.Accept.Clear(); 
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
 
        var content = new StringContent("POSTDATA"); 
        var task = httpClient.PostAsync("/Token", content); 
 
        task.Wait(); 
 
        Console.WriteLine(task.Result.Content.ReadAsStringAsync().Result.ToString()); 

但是当使用HttpWebRequest时

       var request = (HttpWebRequest)WebRequest.Create("HTTPSENDPOINT/Token"); 
       var postData = "POSTDATA"; 
        var data = Encoding.ASCII.GetBytes(postData); 
 
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 
        request.Method = "POST"; 
        request.ContentType = "application/x-www-form-urlencoded"; 
        request.ContentLength = data.Length; 
 
        using (var stream = request.GetRequestStream()) // Getting Error in GetRequestStream() method call 
        { 
            stream.Write(data, 0, data.Length); 
        } 
 
        var response = (HttpWebResponse)request.GetResponse(); 
 
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

我遇到了错误

The request was aborted: Could not create SSL/TLS secure channel. 

请指导我在使用 HttpWebRequest 时做错了什么?

请您参考如下方法:

您需要在 调用 WebRequest.Create 方法之前设置 SecurityProtocol 属性。

更新:

让我添加一些细节来解释为什么这是正确的。

查看来自referencesource.microsoft.com 的WebRequest.Create(string) 方法的源代码.

返回值为:

return Create(new Uri(requestUriString), false); 

现在,让我们看一下 Create(Uri, bool) 方法,它从 WebRequestPrefixElement.Creator.Create(Uri) 返回一些对象。

Creator 是 WebRequestPrefixElement 中的一个属性,属于 IWebRequestCreate 类型。 在您的例子中,IWebRequestCreate 将是一个 HttpRequestCreator 对象。

查看HttpRequestCreator.Create方法的代码:

public WebRequest Create( Uri Uri ) { 
    // 
    // Note, DNS permissions check will not happen on WebRequest 
    // 
    return new HttpWebRequest(Uri, null); 
} 

最后,让我们看一下 HttpWebRequest 构造函数。 您会在那里看到很长的代码,但真正重要的是这一行:

SslProtocols = (SslProtocols)ServicePointManager.SecurityProtocol; 

因此 SecurityProtocol 值被分配给名为 SslProtocols 的属性。 因此,很明显,当您调用 Create 方法时,使用了 SecurityProtocol 并将其保存到 HttpWebRequest 对象中,因此更改 SecurityProtocol 在调用 Create 之后 不会更改 HttpWebRequest 对象使用的协议(protocol)。