在cookie感知的WebClient中读取cookie的价值

时间:2014-05-16 17:52:56

标签: c# cookies webclient httpresponse

我使用此答案提供的代码下载网站并与之互动。

https://stackoverflow.com/a/1031335/1689144

// establish the client and base
CookieAwareWebClient client = new CookieAwareWebClient();
client.BaseAddress = @"some_url";

// establish login data
var loginData = new NameValueCollection();
loginData.Add("username", Settings.Default.username.ToLower());
loginData.Add("password", Settings.Default.password);

// begin login
client.UploadValues("/login", "POST", loginData);

我遇到麻烦的地方。我认为CookieContainerNameValueCollection。它不是......我如何阅读CookieContainer的内容?

//NOM NOM NOM cookies
var nomNomCookies = client.CookieContainer;
foreach (var cookie in nomNomCookies)
{
    //test
    Console.WriteLine(cookie.Name + " " + cookie.Value);
}

1 个答案:

答案 0 :(得分:1)

如果你想使用这个hacky解决方案:

public static IEnumerable<Cookie> GetAllCookies(CookieContainer cookieContainer)
{
    var domainTable = (Hashtable)cookieContainer
                            .GetType()
                            .InvokeMember(
                                name: "m_domainTable",
                                invokeAttr: BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance,
                                binder: null,
                                target: cookieContainer,
                                args: new object[] { });

    return domainTable.Keys.Cast<string>()
                .Select(d => cookieContainer.GetCookies(new Uri("http://" + d.TrimStart('.'))))
                .SelectMany(c => c.Cast<Cookie>());

}