【发布时间】:2015-07-02 14:09:27
【问题描述】:
我有以下代码
CookieContainer container = new CookieContainer();
HttpCookieCollection oCookies = HttpContext.Current.Request.Cookies;
for (int j = 0; j < oCookies.Count; j++)
{
HttpCookie oCookie = oCookies.Get(j);
Cookie oC = new Cookie();
// Convert between the System.Net.Cookie to a System.Web.HttpCookie...
oC.Domain = HttpContext.Current.Request.Url.Host;
oC.Expires = oCookie.Expires;
oC.Name = oCookie.Name;
oC.Path = oCookie.Path;
oC.Secure = oCookie.Secure;
oC.Value = oCookie.Value;
container.Add(oC);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/test.ashx");
request.ServicePoint.ConnectionLimit = 100;
request.Timeout = 20000;
//request.Credentials = CredentialCache.DefaultCredentials;
request.ServicePoint.Expect100Continue = false;
request.CookieContainer = container;
request.Method = "POST";
string formContent = "requestName=update&objectId=1&parentId=1";
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
}
try
{
var response = request.GetResponse();
using (var stream = response.GetResponseStream())
{
if (stream == null)
{
throw new Exception("no response");
}
using (var sr = new StreamReader(stream))
{
var content = sr.ReadToEnd();
}
}
}
catch (WebException wex)
{
var pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
throw new Exception(pageContent);
}
}
我试图代表用户将数据发布到页面,这是一个以编程方式发生的过程,并且站点使用表单身份验证,因此代码复制当前 cookie,并将容器添加到 HttpWebRequest .当代码运行时,它会到达调用request.GetResponse() 的行,但此时代码停止,并最终超时。但是,我在它正在调用的页面的 PageLoad 上有一个断点,一旦发生超时,代码就会在此页面的开头使用来自 POST 的正确信息和预期的会话 cookie 命中断点。有谁知道为什么会有一个调用首先导致超时或此时发生了什么?
【问题讨论】:
-
可能是服务器问题:在 HTTP 1.1(这是 WebRequest 使用的)下,数据不必包含在与 POST 命令相同的 HTTP 消息中。服务器必须识别并发送“100 Continue”状态响应。你的服务器会这样做吗?如果不是,那就是问题所在。
-
我已经在 HttpWebRequest 中将 Expect100Continue 设置为 false,这样可以避免这个问题,不是吗?
-
我也有同样的问题。首先
oC.Domain = HttpContext.Current.Request.Url.Host;是错误的。它必须是 webrequest.create 的目标域。我认为问题是使用 localhost 但我找不到解决方案(我的网站不会使用域)
标签: c# asp.net cookies timeout httpwebrequest