我正在使用WebClient登录我的Web客户端方法Wordpress博客:
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request.GetType() == typeof(HttpWebRequest))
{
((HttpWebRequest)request).CookieContainer = cookieContainer;
foreach (Cookie c in cookieContainer.GetCookies(address))
{
Console.WriteLine(" cName: " + c.Name);
Console.WriteLine(" cValue: " + c.Value);
Console.WriteLine(" cPath: " + c.Path);
Console.WriteLine(" cDomain: " + c.Domain);
}
((HttpWebRequest)request).UserAgent = userAgent;
((HttpWebRequest)request).Timeout = timeout;
((HttpWebRequest)request).Accept = accept;
}
return request;
}
[DebuggerNonUserCode()]
protected override WebResponse GetWebResponse(WebRequest request)
{
try
{
WebResponse response = base.GetWebResponse(request);
if (response.GetType() == typeof(HttpWebResponse))
{
foreach (Cookie c in ((HttpWebResponse)response).Cookies)
{
Console.WriteLine(" Name: " + c.Name);
Console.WriteLine(" Value: " + c.Value);
Console.WriteLine(" Path: " + c.Path);
Console.WriteLine(" Domain: " + c.Domain);
}
characterSet = ((HttpWebResponse)response).CharacterSet;
}
return response;
}
catch (System.Net.WebException e)
{
throw e;
}
}
现在,当我尝试登录wordpress时,发送四个cookie和302重定向
Set-Cookie: wordpress_a235c74829f55a618a01c9f088805f08=precmast%7C1318622660%7C45c78363a5062b592b1fe49201fea5a8; path=/wp-content/plugins; httponly
Set-Cookie: wordpress_test_cookie=WP+Cookie+check; path=/
Set-Cookie: wordpress_a235c74829f55a618a01c9f088805f08=precmast%7C1318622660%7C45c78363a5062b592b1fe49201fea5a8; path=/wp-admin; httponly
Set-Cookie: wordpress_logged_in_a235c74829f55a618a01c9f088805f08=precmast%7C1318622558%7Ca28c4bf14832cbbee606cdddcad9e019; path=/; httponly
但是WebResponse只包含2个cookie(wth path = /),当它自动重定向时,它不会再发送2个cookie,所以我无法登录。现在我通过处理重定向和cookie来解决这个问题。来自response.Headers [“Set-Cookie”]和response.Headers [“Location”]。但我想知道还有其他解决方案吗?
实际修复
if (response.GetType() == typeof(HttpWebResponse))
{
if(response.Headers["Location"] != null)
{
cookieContainer.Add(response.ResponseUri, GetAllCookiesFromHeader(response.Headers["Set-Cookie"], response.ResponseUri.Host));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(response.Headers["Location"]);
req.Method = "GET";
req.AllowAutoRedirect = false;
req.CookieContainer = cookieContainer;
req.UserAgent = userAgent;
req.Timeout = timeout;
req.Accept = accept;
return GetWebResponse(req);
}
答案 0 :(得分:1)
试试这个:
request.AllowAutoRedirect = false;
答案 1 :(得分:0)
您想要做的是:
我不确定提供代码示例是否具有建设性。有了这些信息,找到如何自己编写代码比复制和粘贴更有价值。但是,如果您想要任何代码示例,请留下评论。