簡體   English   中英

如何從 HttpResponseMessage 中檢索 Cookie

[英]How to retrieve Cookies from HttpResponseMessage

我在 post 請求中發送表單數據,我知道它返回 cookie,但我的 cookie 變量被返回為空

如您所見,我嘗試使用 GetCookies,但我想知道是否可以在收到 200 響應時從 PostAsync 響應中過濾掉 cookie

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

HttpClient client = new HttpClient(handler);
HttpContent content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(targetURI.AbsoluteUri , content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

我希望 2 個 cookie 返回並存儲在我的 responseCookies 容器中

您的問題中有一些不清楚的方面:您的cookies變量來自哪里,您的handler變量來自哪里? 這些細節對於回答這個問題很重要。

我可以想到您的代碼中有 2 個可能的錯誤部分。 首先,您應該將CookieContainer附加到您的處理程序:

var cookies = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookies };
var client = new HttpClient(handler);
var content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
var response = await client.PostAsync(targetURI.AbsoluteUri, content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

其次(假設您的cookieshandler變量以這種方式初始化),您可能需要為正確的基址( Uri.Host )獲取 cookie:

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()

如果您完全不確定,請檢查這種方法(基於反射的深度檢查)是否設置了 cookie,以及它們是為哪個域設置的。

只是讓你們知道,問題是我沒有對我的表單數據進行編碼。 將內容更改為下面的行。

var content = new FormUrlEncodedContent(formVals);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM