C#使用HttpWebRequest设置cookie
本文关键字:cookie 设置 HttpWebRequest 使用 | 更新日期: 2023-09-27 18:25:33
我正在使用一个名为Ranorex的测试自动化平台。代码是C#。在打开浏览器开始测试之前,我想使用HttpWebRequest为服务器设置一个cookie。
下面是代码。一切顺利。当我使用浏览器查看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();
}
谢谢Chris
您需要在浏览器中设置cookie,而不是在一些随机的web请求中设置cookie。
您可以通过页面上运行的脚本推送cookie,或者如果您可以拦截请求(即使用Fiddler/Fiddler Core),则可以注入cookie来请求。