这是代码:

public static async Task<string> DownloadPageWithCookiesAsync(string url)
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.UseDefaultCredentials = true;
    handler.AllowAutoRedirect = true;
    handler.UseCookies = true;
    handler.CookieContainer = new CookieContainer();
    HttpClient client = new HttpClient(handler);
    HttpResponseMessage response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();

    string responseBody = response.Content.ReadAsString();
    return responseBody;
}

之后 client.GetAsync(url); 运行, handler.CookieContainer 包含7个cookie。我该如何访问它们?

有帮助吗?

解决方案

int loop1, loop2;
HttpCookieCollection MyCookieColl;
HttpCookie MyCookie;

MyCookieColl = Request.Cookies;

// Capture all cookie names into a string array.
String[] arr1 = MyCookieColl.AllKeys;

// Grab individual cookie objects by cookie name.
for (loop1 = 0; loop1 < arr1.Length; loop1++) 
{
   MyCookie = MyCookieColl[arr1[loop1]];
   Response.Write("Cookie: " + MyCookie.Name + "<br>");
   Response.Write ("Secure:" + MyCookie.Secure + "<br>");

   //Grab all values for single cookie into an object array.
   String[] arr2 = MyCookie.Values.AllKeys;

   //Loop through cookie Value collection and print all values.
   for (loop2 = 0; loop2 < arr2.Length; loop2++) 
   {
      Response.Write("Value" + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
   }
}

其他提示

使用CookieContainer的GetCookies方法,指定您想要的cookie。它返回您可以枚举的烹饪店。

尝试:

CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(/*Uri that the cookies are associated with*/));
for(int i = 0; i < cookies.Count; i++)
{
    Cookie c = cookies[i];
    //Do stuff with the cookie.
}

我相信,您也可以用foreach循环迭代烹饪切片。

CookieCollection cookies = handler.CookieContainer.GetCookies(/*blah-blah*/);
foreach (var cookie in cookies.OfType<System.Net.Cookie>())
{
    // process cookies
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top