将Cookie添加到CookieCollection的NullReferenceException

时间:2012-10-26 20:15:13

标签: c# asp.net cookies

我在cookiecontainer.add(OC)中得到了一个nullreference异常;

我不知道我做错了什么,因为我跟随了一个例子:Sending cookies using HttpCookieCollection and CookieContainer而且我或多或少完全跟随它。引用cookie的INDEX和KEY都会发生错误。

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URI);
        request.KeepAlive = true;
        HttpCookieCollection cookieJar = Request.Cookies;
        //foreach (string cookieString in Request.Cookies)
        for(int i = 0; i < cookieJar.Count; i++)
        {
            System.Web.HttpCookie cookie = cookieJar.Get(i);
            Cookie oC = new Cookie();
            oC.Domain = Request.Url.Host;
            oC.Expires = cookie.Expires;
            oC.Name = cookie.Name;
            oC.Path = cookie.Path;
            oC.Secure = cookie.Secure;
            oC.Value = cookie.Value;

            request.CookieContainer.Add(oC);
        }

1 个答案:

答案 0 :(得分:8)

request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(oC);

A CookieContainer is null by default. You must assign a CookieContainer object to the property to have cookies returned in the Cookies property of the HttpWebResponse returned by the GetResponse method. - 的 MSDN