Search code examples
c#httpwebrequestnshttpcookie

C# setting cookie using HttpWebRequest


I'm using a test automation platform called Ranorex. The code is C#. I would like to set a cookie to the server using HttpWebRequest before I open a browser to begin the test.

Below is the code. Everything executes with no problem. When I view the cookies using the browser - mine is not there (there are 54 other cookies) - when I iterate the response as shown below - I only have three (3) cookies.

Your help is appreciated.

This method will execute the test

void ITestModule.Run()
{

  SummaryHelper.KillAllInternetExplorerProcesses(); 

  uri = this.createURI();

  // Using HttpWebRequest to set a cookie to the session
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

  request.CookieContainer = new CookieContainer();            

  Cookie myCookie = new Cookie("mockFlagForTesting", "true", "/", "safeqa.thomson.com");

  request.CookieContainer.Add(myCookie);    


  // Create the processStartInfo obejct to open the IE Browser
  // I expect the cookie to be loaded into the session
  ProcessStartInfo processStartInfo = new ProcessStartInfo(
    @"C:\Program Files\Internet Explorer\iexplore.exe");

  processStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
  processStartInfo.Arguments = uri;
  SummaryBase.process = Process.Start(processStartInfo);

  // Create and set a session cookie. 
  setHTTPCookie();
}



private void setHTTPCookie()
{

  // We will attempt to set the cookie here 
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

  request.CookieContainer = new CookieContainer();  

  Cookie myCookie = new Cookie("mockFlagForTesting", "true", "/", "safeqa.thomson.com");

  // Add the cookie
  request.CookieContainer.Add(myCookie); 

  // Do we need to use POST here to write to the server ?? 
  // Set the request.Method using WebRequestMethods.Http.Get
  request.Method = WebRequestMethods.Http.Get;

  HttpWebResponse response = (HttpWebResponse)request.GetResponse();

  // Iterate the cookies
  // We only display three (3) ?? 
  foreach (Cookie cook in response.Cookies)
  {
    Report.Info("-------------------------------------------------------------");
    Report.Info("cook.Name", cook.Name);
    Report.Info("cook.Value", cook.Value);
    Report.Info("Domain: ", cook.Domain);
    Report.Info("Path: ", cook.Path);
  }            

  response.Close();   
}

Thanks Chris


Solution

  • You need to set cookie in browser, not on some random web request.

    You can either push cookies via script running on the page OR inject cookies to request if you can intercept requests (i.e. using Fiddler/ Fiddler Core).