gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:31:34 31 4
gpt4 key购买 nike

在控制台应用程序中,尝试访问使用 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.comWebRequest.Create(string) 方法的源代码.

返回值为:

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

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

CreatorWebRequestPrefixElement 中的一个属性,属于 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)。

关于c# - 将 HttpClient 和 HttpWebRequest 用于 Https TLS1.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376575/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com