1

I was wondering how to go about setting up a single global variable which would be easily accessible for commands in all webpages of an ASP.net website.

Would this be done through a class, and how would I go about calling it?

An example being holding a unique user ID but being able to use that ID for SQL queries on all webpages.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
james mews
  • 25
  • 3

2 Answers2

4

The obvious place would be the Session.

so for example

Session["MyId"] = 99; // to set it

and

myId = Session["MyId"]; // to get it

Sometimes Sessions fall over though.. So another place would be Cookies - assuming it's not sensitive data..

 // Setting a cookie
 HttpCookie myCookie = new HttpCookie("MyID");
 DateTime now = DateTime.Now;

 // Set the cookie value.
 myCookie.Value = now.ToString();
 // Set the cookie expiration date.
 myCookie.Expires = now.AddMinutes(1);

 // Add the cookie.
 Response.Cookies.Add(myCookie);

you can read the cookie by:

 HttpCookie myCookie = Request.Cookies["MyId"];
 myId = myCookie.Value;
Darren Wainwright
  • 30,247
  • 21
  • 76
  • 127
1

It really depends on the specific scenario. You have a wide range of options that will give you different behaviors.

Usually for ID's that become parameters of commands, you would include those as query string parameters when generating the link to convey them between pages. I.e. if you had an admin page for editing users, you might generate a list of links with URL's like:

/Users/Edit.aspx?userID=123
/Users/Edit.aspx?userID=789

For the current user's ID, that should be provided by your authentication mechanism. For example(maybe different for your scenario depending on how you authenticate): ASP.NET Membership: Where is Current User ID Stored?

From there, any other user level information could be in tables related to the user ID via foreign key.

Session[] is good for temporary storage for the current user. The reason it should be considered temporary is it will expire or be lost if the application pool is recycled. In which case it's usually fine, because the user will have to relogin and start over wherever they were at anyhow. Just don't store anything really important.

You can use static classes+static property to store system wide information.

I would avoid cookies as a last resort. The only cookies involved in any of my apps are the ones that the authentication framework creates automatically, and I never touched them directly. There's a lot of scenarios you have to consider regarding malicious manipulation of cookies, either by the user or by a third party.

Community
  • 1
  • 1
AaronLS
  • 37,329
  • 20
  • 143
  • 202