1

Is it possible to create a variable that is global for each session in ASP.NET? Usually I do this with Session:

Session("my_variable") = 10

But this necessitates casting it every time I want to use it like so:

Dim my_variable as String = CInt(Session("my_variable"))

I see that if I create a Module I can create variables which are public to an entire project for each session...I also see that Global.asax allows for much of the same functionality offered by modules. I'd prefer to avoid writing a module...is there a way to do this in Global.asax or some other best practice method? Or is Session variables the best way?

0

2 Answers 2

2

Create a wrapper class for your variable like this

public class SessionVariables
{

  public static int MyVariable
  {
     get{ return if( Session["my_variable"] != null ) (int)Session["my_variable"]; else 0;}
     set {Session["my_variable"] = value;}
   }


}

And use like

SessionVarible.MyVariable = 7;

int p =  SessionVarible.MyVariable + 3;
Sign up to request clarification or add additional context in comments.

Comments

1

If you just want to store/retrieve data in the session scope, then the Session object is the way to go. HttpModules are useful for implementing some feature that's tied to specific points in the ASP.NET request pipeline (eg, say you wanted to add logging on authentication requests). Global.asax lets you do similar, and is probably good enough for your purposes (just implement the event you want to target in global.asax).

If you're worried about boxing/unboxing from object, then I like hkutluay's idea of using a wrapper class that hides the cast.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.