CookieContainer 事故

CookieContainer mishap

为了更好的可读性,我对其进行了编辑。这也是不一样的question

此代码的目的是将 CookieContainer 对象转换为 HashTable,以便稍后转换为 CookieCollection。我收到此代码

的错误 "Cannot find variable 'm_domainTable'"
var cookieJar = new CookieContainer();
cookieJar.Add(new Uri("http://someuri.com"), new Cookie("name", "value", "/path/", ".domain"));
var table = (Hashtable) cookieJar.GetType().InvokeMember("m_domainTable",
            BindingFlags.NonPublic |
            BindingFlags.GetField |
            BindingFlags.Instance,
            null,
            cookieJar,
            new object[] {});

甚至使用此 hack 的目的是能够循环访问本地存储的 cookie 文件。我尝试使用下面建议的代码创建一个新项目,但出现错误 "Object not set to an instance of an Object".

var cookieJar = new CookieContainer();
var table = (Hashtable)cookieJar.GetType()
        .GetField("m_domainTable", BindingFlags.NonPublic | BindingFlags.Instance)
        .GetValue(cookieJar);

所以我卡住了。之前我已经展示了我的 SendPost() 方法,但是由于这个错误只涉及这些代码,所以我去掉了那个方法。如果您需要更多代码或需要我测试任何内容,请告诉我,我很乐意让它正常工作。

我的环境设置是使用 Mono/.Net 4.5 的 MonoDevelop,使用这些程序集:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;

嗯,你可以像

一样访问这个私有字段
var table = (Hashtable)cookieJar.GetType()
                .GetField("m_domainTable", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(cookieJar);

更新

我在你原来的问题中遗漏了 mono 标签。但是由于您的工作环境是 Mono,而不是 Microsoft CLR - 那么您可能看错了方向。

据我所知 - m_domainTable 哈希表仅存在于 Microsoft 实现中,但不存在于 Mono 中。

可以通过简单的测试代码来证明:

var cookieJar = new CookieContainer();
var type = cookieJar.GetType();
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

foreach (var field in fields)
    Console.WriteLine(field.ToString());

然后在Microsoft CLR中为运行,它输出:

System.Collections.Hashtable m_domainTable
Int32 m_maxCookieSize
Int32 m_maxCookies
Int32 m_maxCookiesPerDomain
Int32 m_count
System.String m_fqdnMyDomain

但是如果你在 Ideone 中 运行 它(我想它是 运行ning Mono 那里),你会得到:

System.Int32 capacity
System.Int32 perDomainCapacity
System.Int32 maxCookieSize
System.Net.CookieCollection cookies

看看这里:System.Net.CookieCollection cookies - 看来这里是您需要的字段....