我遇到了C#和简单的HTTPS-Request ...
的问题我想请求这个网址:https://api.sipgate.com/v1/在网络浏览器中,它工作正常,但我的C#-Code不起作用:(有人知道我做错了什么吗?谢谢!
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());
}
以下是例外:
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.
System.Net.WebException:
身份验证出错,因为另一方已关闭传输流。
答案 0 :(得分:7)
您缺少对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;
};
答案 1 :(得分:1)