HttpClient自動爲您管理身份驗證Cookie。只要確保你重複使用同一個HttpClient實例來處理多個請求。在封面下,HttpClient創建一個具有CookieContainer的HttpClientHandler實例。
這是一個登錄到NerdDinner站點並檢索受保護頁面的示例。
var httpClient = new HttpClient();
// Create login payload
var body = new Dictionary<string, string>()
{
{"UserName", "bob"},
{"Password", "xyz"},
{"RememberMe", "false"}
};
var content = new FormUrlEncodedContent(body);
// POST to login form
var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content);
// Make new request to secured resource
var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My");
var stringContent = await myresponse.Content.ReadAsStringAsync();
一直在嘗試這個,看起來我實際上正在某處! :D – Jazerix
@Jazerix不要忘記使用AMR建議的HTML Agility Pack –