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!
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.
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.
No, it is not shared.
No they can not. Session information is stored server-side not client-side.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With