Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Session vs. Static class for saving user data

I'm working on an ASP.NET website with a C# backend. De webserver is running on a remote server, and because I need some data located on the client's pc (for instance: the user id), I wrote a client and server application. So when the user starts the client application, it connects to the webserver but doesn't load the page yet, the webserver launches my server which asks the client for some data. After the client responds, the server has the required data and the webpage loads for the client.

To easily access some properties from the user, I wanted to use the Session variables. But when the client sends its data to the server, the Session variable isn't available yet. When I try to access it I get a NullReferenceException. I believe this is because the Application_AcquireRequestState event isn't fired yet (located in Global.asax.cs). Because I need to use the client's data, I save it in a static class so I can access it easily at any time.

Is there a better solution to this? I thought of waiting for the Application_PostAcquireRequestState event to fire, because I think the Session variable is available at that time. So I could then load the data from the static class into the user's session variable. Is this a good idea, or should I just stick with the current situation (static class)? Because it works, but it doesn't feel like the best way to do this.

Thanks in advance!

like image 406
Carlito Avatar asked Jan 05 '12 10:01

Carlito


People also ask

What should not be stored in session?

Things like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you. Save this answer.

Should I use session variables?

If the answer is "the current value", session variables may be useful. An example would be a shopping cart: you don't expect things to be removed from the shopping cart as you go back through the history. It's always in its current state. If the answer is "a previous value", you should not be using session variables.

Is session shared between users?

No, it is not shared.

Can user access session data?

No they can not. Session information is stored server-side not client-side.


1 Answers

Session state is good enough for per-user-session data.

Don't touch statics, these are scoped per AppDomain in a process. IIS will recycle AppDomains without you knowing, binning your static variables.

Update: for the sake of clarity, the following question/answer explains a situation where Session will be null:

What should I do if the current ASP.NET session is null?

This obviously makes Session state unsuitable if your application falls into one of the aforementioned situations.

like image 117
Adam Houldsworth Avatar answered Sep 26 '22 15:09

Adam Houldsworth