Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest Cookies not being set

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
like image 977
Daniel Perez Avatar asked Dec 22 '10 09:12

Daniel Perez


1 Answers

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;
   }
like image 84
Daniel Perez Avatar answered Sep 28 '22 06:09

Daniel Perez