繁体   English   中英

对存储在Cookie中的会话数据对象进行反序列化和序列化

[英]Deserialize & Serialize Session Data Object Stored in a Cookie

我正在尝试将会话数据存储在Cookie中。 这个想法是将相当小的对象作为json字符串存储在cookie中。 我正在使用在该线程的答案中找到的类示例的修改版本:

ASP.NET会话访问的这种技术是否对多用户安全?

这是我正在尝试的...

using System;
using Newtonsoft.Json;
using System.Web;

namespace SomeNameSpace
{
public class MySession
{
    // private constructor
    private MySession()
    {
        SomeString = string.Empty;
        MyDate = DateTime.Now;
        UserId = 0;
    }

    // Gets the current session.
    public static MySession Current
    {
        get
        {
            MySession session = null;
            if (HttpContext.Current.Request.Cookies["Session"].Value != null)
            {
                // This is where I'm having trouble.  Neither of these work:
                session = JsonConvert.DeserializeObject<MySession>(HttpContext.Current.Request.Cookies["Session"].Value);
                session = (MySession)JsonConvert.DeserializeObject(HttpContext.Current.Request.Cookies["Session"].Value);
            }

            if (session == null)
            {
                session = new MySession();
                HttpContext.Current.Response.Cookies["Session"].Value = JsonConvert.SerializeObject(session);
            }
            return session;

        }
    }

    public string SomeString { get; set; }
    public DateTime MyDate { get; set; }
    public int UserId { get; set; }
}
}

这行:

session = JsonConvert.DeserializeObject<MySession>(HttpContext.Current.Response.Cookies["Session"].Value);

不抛出错误。 但是问题是,它启动了构造函数,因此总是返回具有默认值的对象。

这行:

session = (MySession)JsonConvert.DeserializeObject(HttpContext.Current.Response.Cookies["Session"].Value);

引发错误:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'SomeNameSpace.MySession'

我该如何完成?

谢谢!!

您正在读取键“ Session”的响应 cookie,该响应 cookie在那时尚未设置。 您需要阅读请求 cookie。

话虽如此,如果这是会话数据,则您不想将其存储在用户可读和用户可编辑的Cookie中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM