Click here to Skip to main content
15,891,409 members
Articles / Web Development / ASP.NET
Alternative
Tip/Trick

No More Session Variable Misspellings

Rate me:
Please Sign up or sign in to vote.
3.94/5 (7 votes)
6 May 2019CPOL 7.9K   3   4
This is an alternative for "No More Session Variable Misspellings"

Introduction

I started doing some MVC stuff, and came up with another way that doesn't involve any outward-facing casting to the object's type, AND preserves the strong typing that we all know and love in real programming languages:

Using the Code

I set up a static class called SessionVars that contains a property for each variable.

C#
public static class SessionVars
{
    // provided to simplify typing in the actual session var properties
    public static HttpSessionState Session 
    {
        get
        {
            return System.Web.HttpContext.Current.Session;
        }
    }
    
    public static string MyStringVar
    {
        get
        {
            string value = string.Empty;
            if (SessionVars.Session != null)
            {
                object obj = SessionVars.Session["myStringVar"];
                value = (obj == null) ? default(string) : (string)obj;
            }
        }
        set
        {
            SessionVars.Session["myStringVar"] = value;
        }
    }
}

Keep in mind that this doesn't remove the need for casting, it simply abstracts it away so you can do the following in your code:

C#
string myValue = SessionVars.MyStringVar;

Which is a lot cleaner than doing it this way:

C#
string myValue = (string)(System.Web.HttpContext.Current.Session["myStringVar"]);

You also don't have to worry about how the variable key was spelled, because that's all handled in the property that you defined.

One final note - .NET Core handles the session state quite differently, and while this code won't work in .NET Core, all you have to do is change the property that returns the session state to do it the Core way, and all of the other properties should theoretically work without changes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionSession Var names Pin
RmcbainTheThird8-May-19 3:31
professionalRmcbainTheThird8-May-19 3:31 
QuestionGMTA? Pin
Anke68317-May-19 7:50
Anke68317-May-19 7:50 
QuestionI've been doing this for years Pin
Pong God7-May-19 7:42
Pong God7-May-19 7:42 
SuggestionImproving and boosting session variables Pin
ObiWan_MCC7-May-19 2:59
ObiWan_MCC7-May-19 2:59 
Hi there, I appreciated your post/view, on the other hand, set aside from some "volatile" informations, I've been avoiding session variables for a quite looong time now, in my case, I found that, using the built-in cache object allowed for a better approach, then, since the cache doesn't "scale", one may just wrap the code into a class object (add, remove, enum, and all that); such an approach allows the code to become independent from session timeouts (YOU set the cache expiry, which may also be a "sliding" one) and, at the same time, allows to easily and quickly adapt the code to different caching schemes, for example, one may start with the vanilla .NET caching and, when he needs to escalate to multiple instances, derive the cache class from the base one and implement the code to handle a distributed cache (e.g. "ReDis") all this w/o even touching the application code and, with the advantage of having full control over the "session" (cached state) so that the app will run smoothly w/o any need to change whatever server settings Smile | :) !

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.