gpt4 book ai didi

c# - 简单 HTTPS 请求中的 System.Net.WebException

转载 作者:太空狗 更新时间:2023-10-29 22:36:01 25 4
gpt4 key购买 nike

我遇到了 C# 和一个简单的 HTTPS 请求的问题...

我想请求这个 URL:https://api.sipgate.com/v1/在网络浏览器中它工作正常,但我的 C# 代码不起作用:(有人知道我做错了什么吗?谢谢!

using System.Net;
using System.IO;

// [...]

WebRequest req = WebRequest.Create("https://api.sipgate.com/v1");
req.ContentType = "application/json";

try {
WebResponse res = req.GetResponse(); // Exception here...
Stream content = res.GetResponseStream();
Console.WriteLine((new StreamReader(content)).ReadToEnd());
} catch (Exception e) {
Console.WriteLine(e.ToString());
}

异常(exception)情况:

System.Net.WebException: Die zugrunde liegende Verbindung wurde geschlossen: Unerwarteter Fehler beim Senden.. ---> System.IO.IOException: Fehler bei Authentifizierung, da die Gegenseite den Transportstream geschlossen hat.
bei System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
bei System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
bei System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
bei System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
bei System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
bei System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
bei System.Net.ConnectStream.WriteHeaders(Boolean async)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Net.HttpWebRequest.GetResponse()
bei Sipgate_Test.Program.Main(String[] args) in c:\users\abc\documents\visual studio 2017\Projects\def\hij\Program.cs:Zeile 24.

系统.Net.WebException:

Error in authentication because the other side has closed the transport stream.

最佳答案

您缺少对 SSL 的支持。

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

using (WebClient Client = new WebClient())
string Content = Client.DownloadString("https://api.sipgate.com/v1");

编辑:感谢@Crowcoder 指出这一点。在生产环境中,您永远不应接受未经验证的任何证书。 ServerCertificateValidationCallback 提供了一种访问您通常无法访问的 SSL 证书信息的方法。例如,参数 error 为您提供特定的证书错误,如名称不匹配。参数 chain 为您提供服务器发送的确切证书链,当系统存储缺少中间 CA 证书时,可用于构建证书链。

ServicePointManager.ServerCertificateValidationCallback += 
(s, cert, chain, error) =>
{
return error == SslPolicyErrors.None;
};

关于c# - 简单 HTTPS 请求中的 System.Net.WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873579/

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