C#使用HttpWebRequest设置cookie
我正在使用一个名为Ranorex的测试自动化平台。代码是C#。在打开浏览器开始测试之前,我想使用HttpWebRequest为服务器设置cookie 下面是代码。一切都顺利执行。当我使用浏览器查看Cookie时-我的不存在(还有54个其他Cookie)-当我迭代如下所示的响应时-我只有三(3)个Cookie 谢谢你的帮助 此方法将执行测试C#使用HttpWebRequest设置cookie,c#,httpwebrequest,nshttpcookie,C#,Httpwebrequest,Nshttpcookie,我正在使用一个名为Ranorex的测试自动化平台。代码是C#。在打开浏览器开始测试之前,我想使用HttpWebRequest为服务器设置cookie 下面是代码。一切都顺利执行。当我使用浏览器查看Cookie时-我的不存在(还有54个其他Cookie)-当我迭代如下所示的响应时-我只有三(3)个Cookie 谢谢你的帮助 此方法将执行测试 void ITestModule.Run() { SummaryHelper.KillAllInternetExplorerProcesses();
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,或者如果您可以拦截请求(即使用Fiddler/Fiddler Core),则可以将cookie注入请求中。您是否看过有关如何使用
HttpCookie
创建cookie的示例,你为什么会有其他的期待?您发出web请求与浏览器发出web请求之间没有任何联系(即,如果我向服务器发出请求,您是否希望看到我的cookies?)您感到困惑。您正在HttpWebRequest中设置cookie,但该cookie无法连接到Internet Explorer。对不起,我不熟悉这种Http内容。似乎我应该能够使用HttpWebRequest和/或HttpWebResponse和我的uri(请求和IE会话之间的连接(可能))向服务器写入cookie,以便加载到浏览器中???在C#:-)中,microsoft上的大多数示例(感谢DJ KRAZE)都集中在ASP上,并假设您正在浏览器会话中工作-我正在运行一个可执行文件。。。再一次-欢迎任何评论。我会继续研究的——在6h层有一些聪明的人,我会去和他们交谈:——)