c# - Webrequest 通过 HTTP 但不是通过 HTTPS (SSL) 工作

标签 c# rest ssl webrequest

我们有一个可以在 http 上正常工作的休息服务。我使用以下 C# 代码向其发布数据:

    string postData = [contains the data to post]
    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    var baseAddress = "http://www.myserver.net/rest/saveData";
    System.Net.WebRequest req = System.Net.WebRequest.Create(baseAddress);
    string authInfo = "username:password";
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    req.Headers["Authorization"] = "Basic " + authInfo;
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
    req.ContentLength = bytes.Length;

    System.IO.Stream os = req.GetRequestStream();
    os.Write(bytes, 0, bytes.Length); //Push it out there
    os.Close();

    System.Net.WebResponse resp = req.GetResponse();
    var s = resp.GetResponseStream();

    var sr = new System.IO.StreamReader(s);
    var r= sr.ReadToEnd().Trim();

现在,如果将其更改为 SSL,则将 http 调用替换为 https 调用:

"https://www.myserver.net/rest/saveData";

这不起作用,因为它在 GetReponse 调用时超时。一开始我以为是自签名证书引起的,但我用的时候不是这样的:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

接受所有证书。我得到的错误类似于传输层返回的零字节(这是我的语言,所以我不知道英语异常是什么)

我在命令行上使用 CURL 来测试调用,它在 http 和 SSL 上都有效,所以其余服务似乎没问题。

有人知道为什么它不能通过 SSL 工作吗?

谢谢

最佳答案

我找到了问题的原因。其余服务使用 SSL3 而不是 TLS。通过添加以下代码:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

问题解决了。

关于c# - Webrequest 通过 HTTP 但不是通过 HTTPS (SSL) 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004497/

相关文章:

java - Neo4j Rest graphdb 连接到远程 heroku 实例时挂起

Javamail 和 TLS? (不是 STARTTLS)

security - 使用散列和盐通过 SSL 进行身份验证

c# - 如何在 LINQ 查询中空检查 c# 7 元组?

c# - 用户控制 + ViewModelBase

c# - 如何在 C# 中加速 WinForms 的显示?

c# - 创建列表的副本

android - 集成 Wordpress 授权并与 Android 登录

ios - 从 Swift 函数中的异步调用返回数据

JAVA TLS SOCKETS : bufferedreader. ready() 始终为 false