[英]WebClient Does not automatically redirect
使用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請求。
我的WebClient處理程序
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
。
鑒於HttpWebRequest
不是瀏覽器,這應該不足為奇。 如果您需要執行這些重定向,請檢查HttpWebResponse.StatusCode ,如果它是300的重定向代碼,則發出另一個請求。 請注意10.3重定向3xx下的鏈接:
此類狀態代碼指示用戶代理需要采取進一步操作才能完成請求。 當且僅當第二個請求中使用的方法是GET或HEAD時,所需的操作可以由用戶代理執行而不與用戶交互。 客戶端應該檢測無限重定向循環,因為這樣的循環會為每個重定向生成網絡流量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.