在执行POST时,无法将HttpWebRequest超时设置为高于100秒?

the*_*ein 12 c# timeout http-post httpwebrequest

我遇到了一个问题,HttpWebRequest在执行POST时不会尊重超过100秒的超时值.但是,如果请求是GET,则会遵循高于100秒的超时值.在.GetResponse()调用时抛出超时异常.我正在设置我能够发现的所有超时值,但似乎我错过了一个,或者框架中有一个错误.

这是一个针对.NET Framework 3.5的C#应用​​程序,使用Visual Studio 2008构建.Web服务器是IIS 6.0,连接超时设置为默认的120秒,启用了保持活动...再次GET请求尊重超时值I指定,如果<= 100秒,POST请求将遵守超时.

这是我的代码:

int timeout = 200000; // 200 seconds
HttpWebRequest proxyRequest = (HttpWebRequest)WebRequest.Create(serverUrl);
proxyRequest.Accept = clientRequest.AcceptTypes.ToDelimitedString(", ");
proxyRequest.Method = "POST"
proxyRequest.UserAgent = clientRequest.UserAgent;
proxyRequest.Timeout =  timeout;
proxyRequest.ReadWriteTimeout = timeout;
proxyRequest.KeepAlive = false;
proxyRequest.AllowAutoRedirect = false;
proxyRequest.ServicePoint.Expect100Continue = false;
proxyRequest.ServicePoint.MaxIdleTime = timeout;
proxyRequest.ServicePoint.ConnectionLeaseTimeout = -1;

try
{
    // add post data
    request.ContentType = "application/x-www-form-urlencoded";
    byte[] postData = Encoding.UTF8.GetBytes("somedata=7&moredata=asdf");
    // set some post data
    request.ContentLength = postData.Length;
    using (Stream stream = request.GetRequestStream())
    {
        stream.Write(postData, 0, postData.Length);
        stream.Close();
    }

    // UPDATE
    // don't set Timeout here! It will be ignored
    // proxyRequest.Timeout = timeout;

    // Timeout exception thrown here if GetResponse doesn't return within 100 seconds
    // even though the Timeout value is set to 200 seconds.
    using (HttpWebResponse proxyResponse = (HttpWebResponse)proxyRequest.GetResponse())
    {
        using (Stream stream = proxyResponse.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.Default))
            {
                string content = reader.ReadToEnd();
                [other pointless code for this example]
                reader.Close();
            }
            stream.Close();
        }
        proxyResponse.Close();
    }
}
finally
{
    proxyRequest.Abort();
}
Run Code Online (Sandbox Code Playgroud)

当我将超时值设置为5秒时,我将在5秒后收到超时异常,正如人们所期望的那样.这证明Timeout值未被完全忽略.

还有其他人遇到过这个问题吗?使用Async版本的GetResponse会解决这个问题吗?任何和所有的想法都欢迎,我已经坚持了几天.

UPDATE

如果我不发布任何数据(这不是很有用),我可以让POST尊重超时值.但是,只要我发布任何数据并且ContentLength> 0,它就会超过100秒.此外,不涉及代理.

更新2

将POST数据添加到示例中,并在不设置Timeout属性的位置添加注释

the*_*ein 24

我想到了.这是一个DRY编码回来并咬我的屁股的例子.上面的代码是我的真实代码的解释,因此上面的代码将正常工作.

问题是我在调用proxyRequest.GetRequestStream()以添加POST数据后设置了Timeout值.因为我正在设置TimeoutReadWriteTimeout属性,所以最短的超时是赢.在POST请求的情况下,即使框架让我在调用GetRequestStream之后设置Timeout值,它也会忽略设置的任何值(而是使用默认的100秒,即使在设置它之后检查Timeout属性显示它是设置为我所期望的).我希望设置Timeout属性与设置ReadWriteTimeout属性相同:如果在调用GetRequestStream后尝试设置ReadWriteTimeout属性,则会抛出异常.如果Timeout做了同样的事情,那将节省我一点时间.我应该早点抓住这个,但我会把它归结为学习经验.

故事的寓意:在创建HttpWebRequest时立即设置所有超时属性.

  • 6年后,在我阅读你的解决方案之前,我失去了几个小时处理同样的问题.谢谢! (3认同)