Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Static Variables shared in a Web Session

I have an mvc webapi service setup that pulls and pushes data from an sql server database.

Within the Web project holding the webapi I have a Static class that just holds some global variables that are accessed from the webapi methods. Following is a very cutdown example of the static class:

public static class SystemProperties
{
    public static int currentContactID;
}

When the WebApi is accessed I strip the ContactID from the Http Headers of the call and set the SystemProperties.CurrentContactID to it.

Than in the methods of the webapi I access SystemProperties.CurrentContactID for data calls.

I have found a problem when there is concurrent webapi calls the currentContactID is getting mixed up.

My question is, how is the static class members shared between calling sessions? Is it going to be pretty much last in best dressed and if the previous person is still in there than they will get screwed over by the new person who will overwrite the variables with their details?

Should I be using a different method to store these details?

Thanks in advance

like image 494
Matt Avatar asked Oct 21 '22 23:10

Matt


1 Answers

You can use the Current HttpContext to store items to use across the lifetime of an HttpRequest

HttpContext.Current.Items["currentContactID"] = value

So you can grab the data from the Request header, and store it here and it will be available for the duration of the current http web request for that user. Every http request has its own Items dictionary so it won't be overwritten by simultaneous requests

If you need to store a variable across several requests for the same user you need to look into cookies or sessions.

like image 161
SlaterCodes Avatar answered Oct 24 '22 11:10

SlaterCodes