繁体   English   中英

使用HttpWebRequest的C#设置cookie

[英]C# setting cookie using HttpWebRequest

我正在使用一个名为Ranorex的测试自动化平台。 代码是C#。 在打开浏览器开始测试之前,我想使用HttpWebRequest为服务器设置cookie。

下面是代码。 一切执行都没有问题。 当我使用浏览器查看cookie时-我的不存在(还有54个cookie)-当我如下所示迭代响应时-我只有三(3)个cookie。

感谢您的帮助。

该方法将执行测试

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

谢谢克里斯

您需要在浏览器中设置Cookie,而不是在某些随机Web请求上设置Cookie。

您可以通过页面上运行的脚本推送cookie,也可以注入cookie以请求是否可以拦截请求(即使用Fiddler / Fiddler Core)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM