這裏是工作示例:
此類擴展默認.NET Web客戶端與存儲cookie能力:
public class CookieAwareWebClient : WebClient
{
public void Login(string loginPageAddress, NameValueCollection loginData)
{
var parameters = new StringBuilder();
foreach (string key in loginData.Keys)
{
parameters.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(loginData[key]));
}
parameters.Length -= 1;
var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var buffer = Encoding.ASCII.GetBytes(parameters.ToString());
request.ContentLength = buffer.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
var container = request.CookieContainer = new CookieContainer();
using (var response = request.GetResponse())
{
CookieContainer = container;
}
}
public CookieAwareWebClient(CookieContainer container)
{
CookieContainer = container;
}
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieContainer CookieContainer { get; private set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
您可以使用它像這個:
protected CookieAwareWebClient GetAuthenticatedClient()
{
var client = new CookieAwareWebClient();
var loginData = new NameValueCollection
{
{ "Email", "[email protected]" },
{ "Password", "testPassword" }
};
client.Login("https://myurl.com/login", loginData);
return client;
}
然後導航到一些內部pa ge使用:
using (var client = GetAuthenticatedClient())
{
var html = client.DownloadString("https://myurl.com/internalPage");
//do your stuff with received HTML here
}
我在我的ASP.NET項目中成功使用該邏輯。
看看[this](http://stackoverflow.com/a/22262976/1768303)。它適用於控制檯應用程序,我希望它也可以在ASP.NET下工作,儘管我沒有對它進行測試。 – Noseratio