Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate for Session variable in c #, Can we use class and its object to store a value instead of session variable?

I am building a web application. The authentication will be managed by the website, that is not my concern. What i need to store is the UserID in some place.

Once they open the application I will be able to get their UserID. I was previously using a Session variable to store this. Can I create a class say:

static string _UserID;

public static string UserDetails
{
    get
    {
        return _UserID;
    }
    set
    {
        _globalValue = \\value from webpage;
    }
}

and use UserDetails._UserID instead of assigning it to a session variable?! The website's session server is not very reliable so I thought I could use this way. Will this work?

I learnt from the answers that the variables will be overwritten for each user which is not what I want!!

Will it be the same scenario if i create an instance of this class in handler and assign the UserID to it??

are there any other way where I can make its scope limited only to one user i.e UserID with which I login should be same and if new user login to the application it must not be overwritten?? what is the disadvantage of using this method?? Is this method good if I use only one page and assign the object in the launch of the applciation ??

like image 248
Vignesh Subramanian Avatar asked Feb 14 '23 23:02

Vignesh Subramanian


2 Answers

Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class.

The main problem is that static variables are shared across ALL USERS, and that is dangerous in your case that you pretend to store an UserID inside it. If you want to store per user sessoin ID you should use Session

You can find more info here:

Lifetime of ASP.NET Static Variable

like image 61
Carlos Landeras Avatar answered Apr 09 '23 17:04

Carlos Landeras


static filed will be shared between all users that means you would overwrite it for everyone. If you do not want to store it in Session you may store it in cookie (encrypted if security is important).

like image 34
gzaxx Avatar answered Apr 09 '23 16:04

gzaxx