C# 在HttpWebRequest上设置cookie容器会导致超时,但post仍会通过
我有以下代码C# 在HttpWebRequest上设置cookie容器会导致超时,但post仍会通过,c#,asp.net,cookies,timeout,httpwebrequest,C#,Asp.net,Cookies,Timeout,Httpwebrequest,我有以下代码 CookieContainer container = new CookieContainer(); HttpCookieCollection oCookies = HttpContext.Current.Request.Cookies; for (int j = 0; j < oCookies.Count; j++) { HttpCookie oCookie = oCo
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);
}
}
CookieContainer容器=新的CookieContainer();
HttpCookieCollection-oCookies=HttpContext.Current.Request.Cookies;
对于(int j=0;j
我试图代表用户将数据发布到页面上,这是一个程序化的过程,站点使用表单身份验证,因此代码复制当前cookie,并将容器添加到HttpWebRequest
。当代码运行时,它到达调用request.GetResponse()
的行,但此时代码停止,并最终超时。但是,我在它调用的页面的PageLoad上有一个断点,一旦超时发生,代码就会使用POST和会话cookie中的正确信息点击该页面开头的断点。有人知道为什么会有导致先超时的调用,或者此时发生了什么吗?此说明
request.ServicePoint.Expect100Continue = false;
不操作,因为即使尝试从HttpRequestHeaders集合中删除Expect标头,标头也将由实际发出请求时执行的内部“MakeRequestCommand()”添加
要解决此问题,可以使用System.Net.ServicePointManager.Expect100Continue属性关闭Expect100Continue行为
更多解释可能是服务器问题:在HTTP 1.1(WebRequest使用的是HTTP 1.1)下,数据不必包含在与POST命令相同的HTTP消息中。服务器必须识别并发送“100 Continue”状态响应。你的服务器会这样做吗?如果不是,那就是问题所在。我已经在HttpWebRequest中将Expect100Continue设置为false,这样可以避免这个问题,不是吗?我也有同样的问题。首先,
oC.Domain=HttpContext.Current.Request.Url.Host代码>是错误的。它必须是webrequest.create的目标域。我认为问题在于使用localhost,但我找不到解决方案(我的网站不会使用域)。我尝试在代码和web.config设置中添加ServicePointManager.Expect100Continue=false,但我仍然看到此超时发生