Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

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

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...