asp.net:会话中保存的单个会话变量与对象

时间:2009-11-06 13:01:48

标签: asp.net session

我们为复杂的页面提供了各种相关的会话变量,这些变量包含各种各样的内容。目前,这些会话值是单独的页面属性(Guid,String,Integer等)。如果我有一个具有这些属性的可序列化对象并将其保存在会话中,它会更有效吗?

3 个答案:

答案 0 :(得分:5)

这不太可能是一个问题,但您可以考虑在ViewState中存储特定于页面的值。

我创建了一个名为SessionInfo的静态类,它包含对会话变量的访问,例如:

public static class SessionInfo
{
    private const string AUDITOR_ID_KEY = "AUDITOR_ID_KEY";

    private static T GetSessionObject<T>(string key)
    {
        object obj = HttpContext.Current.Session[key];
        if (obj == null)
        {
            return default(T);
        }
        return (T)obj;
    }

    private static void SetSessionObject<T>(string key, T value)
    {
        if (Equals(value, default(T)))
        {
            HttpContext.Current.Session.Remove(key);
        }
        else
        {
            HttpContext.Current.Session[key] = value;
        }
    }

   public static int AuditorId
   {
       get { return GetSessionObject<int>(AUDITOR_ID_KEY); }
       set { SetSessionObject<int>(AUDITOR_ID_KEY, value); }
   }
}

答案 1 :(得分:3)

只要课程小而紧凑且功能不多,就没问题。如果您不需要更频繁地创建值,则可以为此创建不可变结构。在进行任何修改时,您始终可以使用新结构覆盖。

这是一些代码。

    public struct MyStruct
    {
        public string MyProp;
        public MyStruct(string myProp)
        {
            this.MyProp = myProp;
        }
    }

    public MyStruct MyStructInSession
    {
        get
        {
            if (Session["_MyStructInSession"] == null)
            {
                Session["_MyStructInSession"] = new MyStruct("unnamed");
                //or you can throw an exception but that's not adviseble.
                //throw new Exception("Nothing stored in session");
            }
            return (MyStruct)Session["_MyStructInSession"];
        }
        set
        {
            Session["_MyStructInSession"] = value;
        }
    }

答案 2 :(得分:3)

如果性能是一个主要问题,那么您可能希望考虑优化会话内容的序列化。当您扩展到会话服务器或使用SQL Server管理会话状态时,序列化/反序列化成为一个更大的瓶颈。

来自MSDN Magazine

  

会话状态使用自定义   序列化机制转换   会话字典及其内容   存储数据之前的二进制blob   在一个进程外的商店。该   序列化机制有直接的   支持.NET Framework原语   类型,包括String,Boolean,   DateTime,TimeSpan,Int16,Int32,   Int64,Byte,Char,Single,Double,   十进制,SByte,UInt16,UInt32,   UInt64,Guid和IntPtr。这些类型   直接写到blob,   对象类型是序列化的   BinaryFormatter,速度较慢。   反序列化遵循相同的原则   规则。通过优化会话   内容,你可以大大减少   序列化的开销和   国家数据的反序列化。

     

设计会话对象时   模型,避免存储对象类型   会议。相反,只存储   会话中的原始类型   字典和重建您的业务   每个请求上的图层会话对象   基于会话数据。这避免了   使用BinaryFormatter的开销。

与往常一样,在进行任何优化之前先测量您的表现。

相关问题