I'm trying to do some simple stuff, I've already looked at the examples through the web and I'm not sure of what I'm doing wrong
It's a unit test that i'm doing to test some functionality that later will be performed by some different devices
Basically I'm creating a webrequest to my site, which returns a set of cookies, which we later on need
Then I want to create a new webrequest, using the returned cookies from the first response, but when i'm reading that info, the cookies are empty
var request = (HttpWebRequest)WebRequest.Create("http://localhost/bla");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(originalResponse.Cookies); // originalResponse.Cookies has several cookies needed by "bla"
var response = request.GetResponse();
In another place... (inside "bla")
HttpContext.Current.Request.Cookies // this is empty
Ok, found what was happening
THe problem's that we can't just set the cookiecontainer to have the cookies from the response, since it's a new request we need to set the domain that the cookies belong to as well (.net is not assuming that the domain is the one from the URI in the Request object)
so, we need to do something like this when setting the cookies :
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Uri("http://localhost"), originalResponse.Cookies);
Just as another note, i was having a Path problem when setting the cookies.. getting an error like "The 'Path'=/MyApp part of the cookie is invalid". I solved this by setting the cookies' path to nothing before adding them (and making them valid in the whole domain)
for (int i = 0; i < originalResponse.Cookies.Count; i++)
{
originalResponse.Cookies[i].Path = String.Empty;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With