简体   繁体   English

序列化json字符串中的会话对象

[英]serializing session object in json string

I built a strongly typed session object that looks like this: 我建立了一个强类型的会话对象,如下所示:

class MySession
{
  public string UsedID {get;set;}
  public List<int> ListOfInt {get;set;}
  public List<string ListOfString {get;set;}
  .....
}

I'm currently using InProc session so when a page loads, I write: 我当前正在使用InProc会话,因此当页面加载时,我写:

MySession TheSession = Session["UserSession"] as MySession;

and then later in the code I can access each property with TheSession.XYZ syntax. 然后在代码后面,我可以使用TheSession.XYZ语法访问每个属性。

This is really cool but I'm thinking that it might be better to store the session in the DB. 这确实很酷,但我认为将会话存储在数据库中可能会更好。

I'm thinking about serializing the MySession object in a json string and store the string in a DB that I can retrieve and deserialize when a page loads. 我正在考虑序列化json字符串中的MySession对象,并将该字符串存储在数据库中,以便在页面加载时可以检索和反序列化该数据库。

Is this a good way to do it? 这是一个好方法吗?

Thanks for your suggestions. 感谢您的建议。

ASP.NET Session State Server vs. InProc Session covers the pros and cons of using a state server or in-process session storage. ASP.NET会话状态服务器与InProc会话讨论了使用状态服务器或进程内会话存储的优缺点。

As for using JSON, it's certainly more lightweight than XML and just about as flexible - at least for your purposes. 至于使用JSON,它肯定比XML轻巧,并且几乎一样灵活-至少出于您的目的。 I see no reason not to go with it. 我认为没有理由不这样做。

First of all make sure you need all the data in Session. 首先,确保您需要Session中的所有数据。 I sense that you rather need to create database tables and store data in the tables. 我认为您宁愿创建数据库表并将数据存储在表中。

If you are sure that you need Session, then it would make sense to use standard <sessionState mode="SQLServer"> . 如果确定需要Session,则可以使用标准的<sessionState mode="SQLServer"> You can read more about Session-State Modes here . 您可以在此处阅读有关会话状态模式的更多信息。

If you are sure you want custom serialization, then it would make sense to use binary serialization instead of JSON. 如果确定要自定义序列化,则使用二进制序列化而不是JSON是有意义的。 It will need less memory to store and less resources to serialize/deserialize. 它将需要较少的内存来存储,并且需要较少的资源来进行序列化/反序列化。

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

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