2012-11-10 60 views
70

我已經得到了下面的代碼可以成功運行。我無法弄清楚如何從響應中獲取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; 
      } 
+0

出於好奇,我可以問你爲什麼要讀取客戶端上的cookies嗎?我的理解是,Cookie用於將信息發送到服務器,而不是用於返回信息。 –

+0

我在返回JSON的調用上使用返回的cookie,以便我不必爲每個JSON調用執行單獨的授權調用。也就是說,我有一個調用日誌/ Home/GetData,它返回JSON,但只有在獲得授權的情況下才會返回。在客戶端請求上,我添加了cookie,以便/ Home/GetData進行響應。否則它會說「403」未經授權。 –

+0

將授權標頭設置爲默認標頭幾乎同樣有效,並且更加標準。服務器無法代表客戶端自動設置auth頭文件。 –

回答

127

要與CookieContainer.Add(uri, cookie)請求之前Cookie添加到請求,填充餅乾的容器。請求完成後,cookie容器將自動填充響應中的所有cookie。然後你可以調用GetCookies()來檢索它們。

CookieContainer cookies = new CookieContainer(); 
HttpClientHandler handler = new HttpClientHandler(); 
handler.CookieContainer = cookies; 

HttpClient client = new HttpClient(handler); 
HttpResponseMessage response = client.GetAsync("http://google.com").Result; 

Uri uri = new Uri("http://google.com"); 
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>(); 
foreach (Cookie cookie in responseCookies) 
    Console.WriteLine(cookie.Name + ": " + cookie.Value); 

Console.ReadLine(); 
+2

注意:在第一次通話中接收到初始cookie後,當訪問來自同一個域的任何頁面時,cookies將自動發送,不需要額外的步驟。 – Jahmic

相關問題