Asp.net: individual session variables versus object stored in the session

We have various related session variables for a complex page that has different things. These session values ​​are currently separate page properties (Guid, String, Integer, etc.). If I had a serializable object with these properties and saved it in a session, would it be more efficient?

+3
source share
3 answers

This is unlikely to be a problem, but you might consider storing page-specific values ​​in the ViewState.

I create a static SessionInfo class that transfers access to session variables, for example:

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); }
   }
}
+5
source

, . , , - . .

.

    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 not adviseble.
                //throw new Exception("Nothing stored in session");
            }
            return (MyStruct)Session["_MyStructInSession"];
        }
        set
        {
            Session["_MyStructInSession"] = value;
        }
    }
+3

, . / , SQL Server .

MSDN:

. .NET Framework , String, Boolean, DateTime, TimeSpan, Int16, Int32, Int64, Byte, Char, Single, Double, Decimal, SByte, UInt16, UInt32, UInt64, Guid IntPtr. blob, BinaryFormatter, . . , .

When developing a model session object, avoid storing object types in a session. Instead, just store the primitive types in the session dictionary and rebuild your business session object layers for each request based on the session data. This avoids the overhead of using BinaryFormatter.

As always, first measure your performance before making any optimizations.

+3
source

Source: https://habr.com/ru/post/1722104/


All Articles