我有以下代码
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);
}
}
我正试图代表用户将数据POST到页面上,这是一个程序化的过程,网站使用表单身份验证,因此代码复制当前cookie,并将容器添加到HttpWebRequest
中。当代码运行时,它到达调用request.GetResponse()
的行,但此时代码停止,并最终超时。然而,我在它调用的页面的PageLoad上有一个断点,一旦超时,代码就会像预期的那样,用POST和会话cookie中的正确信息到达该页面开头的断点。有人知道为什么会有一个呼叫首先导致超时,或者此时发生了什么吗?
此指令
request.ServicePoint.Expect100Continue = false;
不起作用,因为即使您尝试从HttpRequestHeaders集合中删除Expect标头,该标头也将由实际发出请求时执行的内部"MakeRequestCommand(("添加。
若要解决此问题,可以使用System.Net.ServicePointManager.Expect100Continue属性关闭Expect100Continue行为。
此处的更多解释