HttpWebRequest: Add Cookie to CookieContainer -> ArgumentException (Parametername: cookie.Domain)

C#CookiesHttpwebrequestWebrequest

C# Problem Overview


I'm trying to login to a website via my application. What I did:

First I figured out how the browser does the authorization process with Fiddler. I examined how the POST request is built and I tried to reconstruct it. The browser sends 4 cookies (Google Analytics) and I tried to set them:

CookieContainer gaCookies = new CookieContainer();
gaCookies.Add(new Cookie("__utma", "#########.###########.##########.##########.##########.#"));
gaCookies.Add(new Cookie("__utmb", "#########.#.##.##########"));
gaCookies.Add(new Cookie("__utmc", "#########"));
gaCookies.Add(new Cookie("__utmz", "#########.##########.#.#.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"));

(just replaced the original cookie data with #)

Then I went through the code with the debugger and as soon as the first gaCookies.Add is executed, the application stops with an

System.ArgumentException: The parameter '{0}' cannot be an empty string. Parameter name: cookie.Domain

I would like to know why this happens. The constructor of Cookie doesn't require a domain and I don't know where I can get this value?

Would be very great if someone of you could help me with this.
I'm not a webdeveloper or an expert in web stuff so I don't know much about it.
Is there maybe a great source where I can learn about this if there is no "short and quick answer"?

C# Solutions


Solution 1 - C#

CookieContainers can hold multiple cookies for different websites, therefor a label (the Domain) has to be provided to bind each cookie to each website. The Domain can be set when instantiating the individual cookies like so:

Cookie chocolateChip = new Cookie("CookieName", "CookieValue") { Domain = "DomainName" };

An easy way to grab the domain to is to make a Uri (if you aren't using one already) that contains your target url and set the cookie's domain using the Uri.Host property.

CookieContainer gaCookies = new CookieContainer();
Uri target = new Uri("http://www.google.com/");

gaCookies.Add(new Cookie("__utmc", "#########") { Domain = target.Host });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTorbenJView Question on Stackoverflow
Solution 1 - C#Ichabod ClayView Answer on Stackoverflow