Reputation: 334
I have an application where I save some information on the session that later I assign to the model when I save it to the DB. For example I have the following model saved by User1:
...
MyModel model = new MyModel();
model.name = mypostedModel.name;
model.type = HttpContext.Session.GetString("UniqueTypeForThisUser");
...
After I save the model in my DB, at the end of the post method, I clear the session with this line:
HttpContext.Session.Clear();
Let's say at the same time there's a User2 creating a new model and I have saved another value in the session with a unique key for User2. Same way as before, at the end of the post method I clear the session with the Clear() method.
Does this clear session method clear the session for all users, or only for one user. If for example User1 saves the model first and clears the session for all users, then the User2 will get his session variable cleared (lost) and will assign a null value to my 'type' column for the model.
For the documentation this was not clear for me. Thanks
Upvotes: 4
Views: 17697
Reputation: 2252
You Can remove specific keys
HttpContext.Session.Remove("YourSessionKey");
Upvotes: 6
Reputation: 388273
The session object that you can access for example through HttpContext.Session
is specific to a single user. Everything you do there will only affect the user that belongs to this session and there is no mix between sessions of other users.
That also means that you do not need to choose session configuration key names that are somewhat specific to a user. So instead of using GetString("UniqueTypeForThisUser")
, you can just refer to the values using a general constant name:
var value1 = HttpContext.Session.GetString("Value1");
var value2 = HttpContext.Session.GetString("Value2");
Each user session will then have these values independently. As a result, calling Session.Clear()
will also only clear the session storage for that session that is specific to its user.
If you actually do need different means for storing state, be sure to check out the docs on application state. For example, things that should be stored independently of the user can be stored using an in-memory cache.
Upvotes: 2
Reputation: 29919
Does this clear session method clear the session for all users, or only for one user.
The HttpContext
is the one for the current request. Since every user has a different request, it follows that clearing the session on the current request only clears it for that request's user, not all users.
Upvotes: 1