Search code examples
c#.netcookieshttpwebrequest

HttpWebRequest add cookie exception


I'm trying to create HttpWebRequest with a cookie:

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://myweb.com/get_my_web/");
        req.Method = "POST";

        if (req.CookieContainer == null)
        {
            req.CookieContainer = new CookieContainer();
        }

        System.Net.Cookie newCookie = new System.Net.Cookie("sessionid", AppData.sessionid,
                        "\\", "myweb.com");
        req.CookieContainer.Add(newCookie);

In req.CookieContainer.Add(newCookie); i'm getting this Exception:

An unhandled exception of type 'System.Net.CookieException' occurred in System.dll

Additional information: The 'Domain'='myweb.com' part of the cookie is invalid.

Any idea what is the issue here?


Solution

  • The error message is misleading - problem is in cookie path and not domain. "\\" is invalid path, I think you meant /:

    System.Net.Cookie newCookie = new System.Net.Cookie("sessionid", AppData.sessionid,
        "/", "myweb.com");