Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
572 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...