2

我有一个简单的 winform 应用程序。在第一次运行时,会运行一个登录屏幕,以便用户可以登录到一个网站。如果成功,则保存会话 cookie:

Properties.Settings.Default["cookies"] = cookies;
Properties.Settings.Default.Save();

完成后,登录表单被隐藏并运行一个新的主表单。在这个主窗体中,cookiecontainer 被再次读取并保存:

CookieContainer cookies = Properties.Settings.Default.cookies;

奇迹般有效。会话 cookie 仍然在那里,一切都很好。之后,使用 cookie 向网站发出新请求,如下所示:

private string htmlGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "text/html";
        request.CookieContainer = cookies;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;

    }

工作正常。请求完成并在字符串中找到特定的用户相关数据。

但是,我重新启动程序时发生了一些奇怪的事情。

在程序启动之前,运行此代码以通过查看 cookie 检查首次运行:

if (Properties.Settings.Default.cookies == null)
{
    Application.Run(new login());
}
else
{
    Application.Run(new main());
}

事实上,在第一次运行之后,Properties.Settings.Default.cookiesis not null,所以主窗体开始于Program.cs.

奇怪的是,这一次Properties.Settings.Default.cookies返回一个 CookieContainer 对象……没有 cookie

我不知道为什么,因为我的应用程序设置只保存在登录表单中,该表单仅在第一次运行时打开。有没有人有过 cookiecontainers 做这种奇怪的事情的经验?我是否必须检查我的代码中的某些内容?干杯。

4

0 回答 0