【问题标题】:Converting from saving in Session to Cookies?从保存 Session 转换为 Cookie?
【发布时间】:2011-03-06 08:41:45
【问题描述】:

所以,我正在开发一个演示网络仪表板。以前,我一直使用 Session 来存储有关仪表板的设置,但我想将其移至更持久的保存设置的方式。

在我看来,使用 cookie 是我最好的选择。我并不完全肯定我有时间解决所有问题以正确写入/写入数据库。

话虽如此,我可能对我对 Session 和 Cookie 之间的相似性所做的一些假设感到困惑。

目前,我有一些这样的代码:

public Dictionary<string, RadPageViewSetting> PageViewStates
    {
        get
        {
            Dictionary<string, RadPageViewSetting> _pageViewStates = (Dictionary<string, RadPageViewSetting>)Session["PageViewStates"];
            if (object.Equals(_pageViewStates, null))
            {
                _pageViewStates = new Dictionary<string, RadPageViewSetting>();
                Session["PageViewStates"] = _pageViewStates;
            }

            return _pageViewStates;
        }
        set
        {
            Session["PageViewStates"] = value;
        }
    }

其中 RadPageViewSetting 是一个包含一些我正在记录的属性的类。

cookies 可以实现这个功能吗?如果没有,我应该在哪里通过浏览器关闭来保存我的数据?

编辑:我将使用http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx 来帮助我序列化字典,然后开始序列化我自己的自定义数据超级(RadPageViewSetting)。

编辑:这是我未经测试的解决方案。有人可以快速查看一下,如果它看起来不正确,请告诉我?

        public SerializableDictionary<string, RadPageViewSetting> PageViewStates
    {
        get
        {
            SerializableDictionary<string, RadPageViewSetting> _pageViewStates = new SerializableDictionary<string,RadPageViewSetting>();
            HttpCookie cookie = HttpContext.Current.Response.Cookies["PageViewStates"]; //If the named cookie does not exist, this method creates a new cookie with that name.

            if (object.Equals(cookie, null))
            {
                cookie = new HttpCookie("PageViewStates");
                cookie.Expires = DateTime.Now.AddYears(100);
                cookie.Value = null;
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            else if( cookie.Value != null )
            {
                MemoryStream stream = new MemoryStream();
                StreamWriter writer = new StreamWriter(stream);
                writer.Write(cookie.Value);
                XmlSerializer serializer = new XmlSerializer(_pageViewStates.GetType());
                _pageViewStates = serializer.Deserialize(stream) as SerializableDictionary<string, RadPageViewSetting>;
                HttpContext.Current.Response.Cookies.Set(cookie);
            }

            return _pageViewStates;
        }
        set
        {
            XmlSerializer serializer = new XmlSerializer(value.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.Serialize(stream, value);
            StreamReader reader = new StreamReader(stream);
            HttpContext.Current.Response.Cookies["PageViewStates"].Value = reader.ReadToEnd();
        }
    }

【问题讨论】:

  • 只需修改您的属性以使用 HttpCookie 而不是 Session [并确定您将如何序列化信息](尽管我建议使用 cookie 来存储令牌并在用于实际持久性的数据库(它还取决于您存储的信息类型、受众等))

标签: c# asp.net session cookies


【解决方案1】:

简单地使用 Response.Cookies 代替 Session。

基本上来自 MSDN




Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

您应该能够在 cookie 中存储您喜欢的任何内容,只要您可以将其序列化为字符串即可。因为 cookie 是纯文本。

【讨论】:

  • 您还可以将 cookie 提供程序用作多维数组。 Response.Cookies["userInfo"]["userName"] = "patrick"; Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
  • 注意:cookie 对每个 cookie 的数据大小和 cookie 总数有限制。请注意,您将无法在此处存储任意大量信息。也不要忘记每次请求发送大量数据的性能影响,包括同一域上的 JS/CSS/JPG 文件(除非您仔细管理 cookie 路径/域)。
【解决方案2】:

虽然您接受的答案在技术上有效,但我认为在web.confgsessionState 元素中设置两个属性值可能更容易。

要启用 cookie,请设置 mode="InProc"cookieless="UseCookies"。通过这些配置更改,您无需更改代码中的任何其他内容,因为会话将确保使用 cookie 工作(前提是在客户端的浏览器上启用了 cookie)。

您似乎没有意识到默认情况下 ASP.NET 会话状态对象实际上使用 cookie 来跨多个请求保存数据(尽管可以在您的 web.config 中更改此行为)。

文档

【讨论】:

  • 天哪。非常感谢!我不知道。我学到了很多关于使用 cookie 的知识,但如果 Session 能够以与 cookie 相同的方式持续存在,我可能会坚持使用它。如果我希望能够看到 Session 正在生成的 cookie,我将如何做到这一点?这个想法是我希望能够将 cookie 剪切/粘贴到差异计算机以复制/粘贴网页设置。
  • -1:UseCookie 不会将数据保存在 cookie 中 - 它只会强制使用 cookie 来存储会话 ID。请阅读msdn.microsoft.com/en-us/library/…
  • -1:这些设置是默认的,并且“InProc”将数据存储在内存中,cookie中只有会话ID - 所以在会话到期(或应用程序池回收)后,它是永远消失了——另一方面,cookie 可以永远保存数据
猜你喜欢
  • 2021-01-25
  • 2018-09-21
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
相关资源
最近更新 更多