Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net - Do changes to session objects persist?

Tags:

c#

asp.net

I'm using the session to hold a custom object UserSession and I access the session like this:

UserSession TheSession = HttpContext.Current.Session["UserSession"] as UserSession;

Then, in my code, I modify a property of TheSession like this

TheSession.Prop1 = some new value;

My question is this: when I change the value, does it change the value inside the session that's in HttpContext.Current.Session["UserSession"] or just the TheSession variable, in which case I'd need to reassign the object variable to the session.

Thanks.

like image 430
frenchie Avatar asked Jun 17 '11 02:06

frenchie


People also ask

What is a session object in ASP NET?

Using the Session object is easy and its syntax is identical to classic ASP. However, the Session object is one of the less efficient ways of storing user data, since it is held in memory for some time even after the user has stopped using the application. This can have serious effects on scalability for a very busy site.

How do you persist data in ASP NET?

SUMMARY ASP.NET provides many different ways to persist data between user requests. You can use the Application object, cookies, hidden fields, the Session or Cache objects, and lots of other methods. Deciding when to use each of these can sometimes be difficult.

How does ASP NET Core maintain session state?

ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID, which is sent to the app with each request. The app uses the session ID to fetch the session data. Session state exhibits the following behaviors: Because the session cookie is specific to the browser,...

Why is the session object so bad?

Unfortunately, the Session object earned itself a very bad name in classic ASP because it tied an application to a particular machine, precluding the use of clustering and Web farms for scalability. In ASP.NET, this is less of an issue, since it is a simple matter to change the location where the session is stored.


2 Answers

The standard session provider is a simple dictionary that stores objects in memory.

You're modifying the same object that you put in the session, so the modifications will persist.
(unless you're using an evil mutable struct)

like image 127
SLaks Avatar answered Sep 30 '22 16:09

SLaks


Yes it is the same object. It is very easy to see in the following example:

Session["YourObject"] = yourObject;
yourObject.SomeProperty = "Test";
var objectFromSession = (YourObjectType)(Session["YourObject"]);
Response.Write(objectFromSession.SomeProperty);

The Write will display: Test

like image 41
Kelsey Avatar answered Sep 30 '22 14:09

Kelsey