0

我在 cookiecontainer.add(OC); 处得到一个空引用异常;

我不知道我做错了什么,因为我正在遵循以下示例:使用 HttpCookieCollection 和 CookieContainer 发送 cookie,我或多或少地完美地遵循了它。引用 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);
        }
4

1 回答 1

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

于 2012-10-26T20:20:30.877 回答