我已經得到了下面的代碼可以成功運行。我無法弄清楚如何從響應中獲取cookie。我的目標是,我希望能夠在請求中設置Cookie,並將cookie從響應中取出。思考?努力嘗試讓Cookie無法響應在.net 4.5中的HttpClient
private async Task<string> Login(string username, string password)
{
try
{
string url = "http://app.agelessemail.com/account/login/";
Uri address = new Uri(url);
var postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password ", password)
};
HttpContent content = new FormUrlEncodedContent(postData);
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
return body;
}
catch (Exception e)
{
return e.ToString();
}
}
下面是完整的答案:
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
foreach (Cookie cookie in responseCookies)
{
string cookieName = cookie.Name;
string cookieValue = cookie.Value;
}
出於好奇,我可以問你爲什麼要讀取客戶端上的cookies嗎?我的理解是,Cookie用於將信息發送到服務器,而不是用於返回信息。 –
我在返回JSON的調用上使用返回的cookie,以便我不必爲每個JSON調用執行單獨的授權調用。也就是說,我有一個調用日誌/ Home/GetData,它返回JSON,但只有在獲得授權的情況下才會返回。在客戶端請求上,我添加了cookie,以便/ Home/GetData進行響應。否則它會說「403」未經授權。 –
將授權標頭設置爲默認標頭幾乎同樣有效,並且更加標準。服務器無法代表客戶端自動設置auth頭文件。 –