C# настройка cookie с использованием HttpWebRequest
Я использую платформу автоматизации тестирования под названием Ranorex. Код C#. Я хотел бы установить cookie на сервер, используя HttpWebRequest, прежде чем открывать браузер, чтобы начать тестирование.
Ниже приведен код. Все выполняется без проблем. Когда я просматриваю файлы 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();
}
Спасибо Крис
1 ответ
Вам нужно установить cookie в браузере, а не по случайному веб-запросу.
Вы можете либо отправить файлы cookie с помощью скрипта, запущенного на странице, либо добавить файлы cookie, чтобы запросить возможность перехвата запросов (например, с помощью Fiddler/ Fiddler Core).