我正在使用名爲Ranorex的測試自動化平臺。代碼是C#。我想在打開瀏覽器開始測試之前使用HttpWebRequest將cookie設置爲服務器。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();
}
感謝 克里斯
你有沒有看過如何使用'HttpCookie'創建cookie的例子,看看你是如何創建你的'myCookie'對象的。 – MethodMan 2014-10-02 21:50:44
是的,爲什麼你會期待其他呢?您在進行網絡請求和瀏覽器製作網絡請求時(即,如果向服務器提出請求,您是否希望看到我的cookie?) – 2014-10-02 21:50:46
http://msdn.microsoft.com/zh-cn/library/system .web.httprequest.cookies(v = vs.110).aspx – MethodMan 2014-10-02 21:52:54