ASP.NET WebApi Session vs Static Variables

On ASP.NET WebApi hosted on IIS 7, does it have access to the session? It looks like Session is null on HttpContext.Current .

What is the difference between the two for storing a global variable?

 private static Dictionary<string, string> ConnectionStrings { get { if (HttpContext.Current.Session["ConnectionStrings"] == null) HttpContext.Current.Session["ConnectionStrings"] = new Dictionary<string, string>(); return HttpContext.Current.Session["ConnectionStrings"] as Dictionary<string, string>; } } 

and

 private static Dictionary<string, string> connectionStrings = new Dictionary<string, string>(); 

Should I use session or static variables to store connection strings that are dynamically generated (long history)?

+6
source share
1 answer

Well, the session variable is for every user. A static variable is a variable that will be used by all users. So, I have no idea why to store the connection string for each user, but if you need to do this, you cannot use one static variable. Now you can use the static variable and make it a dictionary, where the key is the user and the value is what you want to save. This will certainly work.

Having said all this, you can simulate sessions using cookies (in the end, this is what sessions use anyway (usually)): See Accessing a Session Using ASP.NET Web API

+6
source

All Articles