c# - 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败

标签 c# asp.net-mvc web-services asp.net-web-api

我有一个问题:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond URL.

我也遇到这样的问题:

System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host

System.Net.WebException: The operation has timed out at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)

我知道以前有人问过这个问题,但请相信我,我最后尝试了几乎每一个解决方案。

奇怪的是这个问题根本没有出现在我这边,只有当客户端尝试使用不是常量的时候才会出现。有时我的应用程序在他们端也能正常工作。

我想要完成的是我创建了一个桌面应用程序(Win Forms 和 C#)并尝试登录客户端,同时向托管在 GODaddy 上的我的 php api 服务器发送请求。

var request = (HttpWebRequest)WebRequest.Create("url");
if (request != null)
{
    #region System.Net.WebException
    request.Method = "POST";
    if (!string.IsNullOrEmpty(body))
    {
        var requestBody = Encoding.UTF8.GetBytes(body);
        request.ContentLength = requestBody.Length;
        request.ContentType = "application/json";
        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(requestBody, 0, requestBody.Length);
        }
    }
    else
    {
        request.ContentLength = 0;
    }
    request.Timeout = 15000;
    request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

    string output = string.Empty;
    try
    {
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    while (!stream.EndOfStream)
                    {
                        output += stream.ReadLine();
                    }
                    output = stream.ReadToEnd();
                }
            }
        }
    }
    catch
    {
        // Excaption Caught here
    }
}

请帮帮我。

提前致谢。

最佳答案

尝试添加这个...

request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 12;

MSDN 文章建议每个 CPU 12 个连接,因此限制为 12 个,因为它由 GoDaddy 托管,所以我确信服务器资源是有限的。

关于c# - 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092375/

相关文章:

c# - 从 C# 向 Java 应用程序 (Minecraft) 发送输入

c# - 将上下文菜单从 App.xaml 附加到 Setter 值

c# - 出于性能考虑更新 N 行

ios - 为什么我无法从网络服务获取数据,我得到反馈“列表不存在”。

c# - 处理 charge.refund webhook 时 Stripe.Net 发票属性为 NULL

c# - 将 RadioButton.IsChecked 与 Listbox.SelectedItem 绑定(bind)

c# - 使用 $.getJson 方法从 jquery 调用 c# mvc Controller 方法

javascript - 安全 MVC Web API Controller

java - ava.lang.NullPointerException : null at org. apache.catalina.loader.WebappClassLoader.findResources(WebappClassLoader.java:1368)~[na:na]

asp.net - ASMX 网络服务 "Server did not recognize the value of HTTP Header SOAPAction"