在c#中获取cookie

本文关键字:cookie 获取 | 更新日期: 2023-09-27 18:19:02

所以,我正在向twitter (RestSharp)发出GET请求,我想收集所有的cookie并将它们放在cookiecollection中,首先我进行GET:

RestClient client = new RestClient("https://mobile.twitter.com");
            RestRequest GetAuth = new RestRequest("/login");
            var GetAuth_Response = client.Get(GetAuth);

现在,我想要得到饼干,我这样做:

 CookieCollection Cookies = GetAllCookies(client.CookieContainer);

>

public static CookieCollection GetAllCookies(CookieContainer container)
{
    var allCookies = new CookieCollection();
    var domainTableField = container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable");            
    var domains = (IDictionary)domainTableField.GetValue(container);
    foreach (var val in domains.Values)
    {
        var type = val.GetType().GetRuntimeFields().First(x => x.Name == "m_list");
        var values = (IDictionary)type.GetValue(val);
        foreach (CookieCollection cookies in values.Values)
        {
            allCookies.Add(cookies);                    
        }
    }          
    return allCookies;
}

现在,当我运行程序时,我得到这个错误:

Additional information: Object reference not set to an instance of an object.

:

var domainTableField = container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable");
谁能帮我这个忙?谢谢,)

编辑:我也试图检查如果如果它是空的,但我仍然得到相同的错误,

if (container.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name == "m_domainTable") != null)

在c#中获取cookie

您可能会得到一个null作为返回值。然后获取name属性将引发异常。你得先检查空值。

 var domainTableFielObject =       container.GetType().GetRuntimeFields().FirstOrDefault() ;
If(domainTableFielObject! =null) 
domainTableField =domainTableFielObject. Where(x => x.Name == "m_domainTable");

我用这段简单的代码修复了我自己的问题:

            foreach (var c in GetAuth_Response.Cookies)
            {
                Cookies.Add(new Cookie(c.Name, c.Value, c.Path, c.Domain));
            }

如果你有同样的问题,替换整个GetAllCookies,只使用^