当使用 Firebug 记录登录过程时,我看到它是这样的
POST //The normal post request
GET //Automatically made after the login
GET //Automatically made after the login
GET //Automatically made after the login
当使用下面的代码发出发布请求时,它没有发出浏览器正在执行的自动 GET 请求。
我的网络客户端处理程序
using System;
using System.Net;
namespace Test
{
class HttpHandler : WebClient
{
private CookieContainer _mContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = _mContainer;
}
return request;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
if (response is HttpWebResponse)
_mContainer.Add((response as HttpWebResponse).Cookies);
return response;
}
public void ClearCookies()
{
_mContainer = new CookieContainer();
}
}
}
使用代码
private static async Task<byte[]> LoginAsync(string username, string password)
{
var postData = new NameValueCollection();
var uri = new Uri(string.Format("http://{0}/", ServerName));
postData.Add("name", username);
postData.Add("password", password);
return await HttpHandler.UploadValuesTaskAsync(uri, postData);
}
当尝试跟踪我的应用程序的连接时,它只执行 POST 请求,而不执行其余的 GET 请求。 [在浏览器中自动生成]
最佳答案
尝试添加
request.AllowAutoRedirect = true;
就在
var request = base.GetWebRequest(address);
它为我解决了一些类似的问题,即使 AllowAutoRedirect
默认情况下应该是 true
。
关于c# - WebClient 不会自动重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039068/