Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebApi Session vs Static Variables

In a ASP.NET WebApi hosted in IIS 7, does it have access to session? It appears Session is null on the HttpContext.Current.

What is the difference between these 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 story)?

like image 431
Sam Avatar asked Feb 11 '13 17:02

Sam


People also ask

Are static variables shared between sessions?

Yes, static values will remain same for all users. if one user is updating that value, then it will be reflected to other users as well.

Can Web API use sessions?

But in practice, yes - you may need to access a user's session from a web API. By default this is not possible.


1 Answers

Well, a session variable is meant to be per user. A static variable is a variable that will be shared between all users. So, I have no idea why would store a connection string per user, but if you need to do that, you can't use one static variable. Now, you could use a static variable and make it a Dictionary, where the key is the user, and the value is whatever you want to store. That would certainly work.

Having said all that, you can mimic sessions using cookies (which ultimately is what sessions make use of anyway (usually)): See: Accessing Session Using ASP.NET Web API

like image 122
aquinas Avatar answered Oct 19 '22 16:10

aquinas