What is the difference between Session.Abandon() and Session.Clear()
Asked Answered
S

10

118

What is the difference between destroying a session and removing its values? Can you please provide an example demonstrating this?

I searched for this question, but don't grasp total answer. Some answers are:

  • Session.Abandon() destroys the session
  • Session.Clear() just removes all values

A friend told me this:

Clearing the session will not unset the session, it still exists with the same ID for the user but with the values simply cleared.

Abandon will destroy the session completely, meaning that you need to begin a new session before you can store any more values in the session for that user.

The below code works and doesn't throw any exceptions.

Session.Abandon();
Session["tempKey1"] = "tempValue1";

When you Abandon() a Session, you (or rather the user) will get a new SessionId

When I test Session, it doesn't makes any change when I Abandon the session.

I just find one difference: session.Abandon() raises Session_End event

Schaeffer answered 24/9, 2009 at 8:41 Comment(1)
Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request.Adenitis
D
158

Clear - Removes all keys and values from the session-state collection.

Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out.
It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.

You say:

When I test Session, it doesn't makes any change when I Abandon the session.

This is correct while you are doing it within one request only.
On the next request the session will be different. But the session ID can be reused so that the id will remain the same.

If you will use Session.Clear you will have the same session in many requests.

Generally, in most cases you need to use Session.Clear.
You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  1. Abandon raises Session_End request.
  2. Clear removes items immidiately, Abandon does not.
  3. Abandon releases the SessionState object and its items so it can ba garbage collected to free the resources. Clear keeps SessionState and resources associated with it.
Dorrisdorry answered 24/9, 2009 at 9:9 Comment(18)
and if i call session.clear() this you tells accures again. not? (all else raising Session_End event)Schaeffer
Session.Clear will only remove items from the Session. Nothing more. You can call it as many times as needed.Dorrisdorry
@AnthonyWJones, you are right "destroy" is incorrect to say. Better is REMOVE objects from session. But Session.Clear also does not destroy objects, it removes thm from session so they can be garbage collected. Also, storing COMPLEX objects is not recommended, otherwise I consider it fine.Dorrisdorry
@Dmitriy: Why "storing COMPLEX objects is not recommended"?Wheelwork
@Dmitriy: Actually I had confused Session with the classic-asp session where is definitely not a good idea to store objects. I would agree though that complex or rather large objects stored in the session may result in scalability concerns.Womble
@Kamarey, storing objects in session MIGHT require it to be serialisable. Complex objects might not always be easily (de)serialised. In addition to that (de)serialisation of complex objects is time and resources consumming process. So in short, for performance and scalability reasonsDorrisdorry
@Dmitriy: in this way if object is not disposable what happens? (do not implement IDisposable Interface) it just omits to be garbage collected?you sure?Schaeffer
@Dmitriy: when i call session.abandone() even in next request session ID is same as when sesion is alive.Schaeffer
@backdoor, I have added the explanation to my answer why you can have the same session id. I'll repeat: Session (and therfore its ID) never changes within one request. At the end of the request the session is thrown away. So next request will have new session and new id.Dorrisdorry
@Dmitriy: and i tell my friend: when i call session.abandone() even in next request session ID is same as when sesion is alive (last post backs...)Schaeffer
Should not be the case unless browser caches your page or cookie for some reason is not removed: technicalsol.blogspot.com/2008/07/… bytes.com/topic/asp-classic/answers/…Dorrisdorry
Actually the session id can be reused (so you have the same id but different session). I added link to the full explanation to my answer.Dorrisdorry
@ Dmitriy: by default SessionID will reused for creating Session on ASP.Net unless you configure it to dont do this. it means that in default situation session.abandon() and session.clear() have not difference else session.abandon() fires Session_End event..?Schaeffer
No there is a difference. Clear removes all the data from session immidiately and preserves the session for further requests. Abandon removes the items at the end of the request, destoys the current session object. So in case you store session in the database you will end up with a new row for the session. While Clear will still use the same row. That is only ID that can be still the same.Dorrisdorry
tanks i've got it... thus just 2 difference there are: 1- raising Session_End event2- clearing SessionObject at the end of processing page instead of immediatly not?Schaeffer
Whenever a user change his/her password, I just call all the 3 functions: Session.RemoveAll() + Session.Clear() + Session.Abondon()Stokehole
+1 for 'meatphora-comparisson'. No idea what it has to so with HttpSessionState, but I am sure it's an awesome method of comparing things.Javierjavler
@Ads I agree, although I would extend it by saying that Session.Clear can be compared to removing all books from the shelf immediately, while Session.Abandon is more like saying "throw away the whole shelf and let me know when you're done".Tatro
T
22

When you Abandon() a Session, you (or rather the user) will get a new SessionId (on the next request). When you Clear() a Session, all stored values are removed, but the SessionId stays intact.

Toth answered 24/9, 2009 at 8:48 Comment(2)
thanks. but accroding to mattew macdonalds book it can use same session id. i means that if regenerateExpiredSessionId attribute at configuration/system.web/sessionState element in web.config file is false ASP.Net uses old session idSchaeffer
@Hans Kesting He will not get a new Session Id when abandon is called. He has to explicitly set the ASPNET_SessionID cookie to null in order to get a new Session ID.Loads
E
9

This is sort of covered by the various responses above, but the first time I read this article I missed an important fact, which led to a minor bug in my code...

Session.Clear() will CLEAR the values of all the keys but will NOT cause the session end event to fire.

Session.Abandon() will NOT clear the values on the current request. IF another page is requested, the values will be gone for that one. However, abandon WILL throw the event.

So, in my case (and perhaps in yours?), I needed Clear() followed by Abandon().

Electrotype answered 15/7, 2011 at 22:51 Comment(4)
Why would you need Session.Clear() followed by Session.Abandon()? You are clearing values of a collection that you are destroying? This is completely redundant. Sure the session object is not immediately destroyed (that happens at the end of the current request), but that session id will no longer be served by any subsequent request. If the client does make a new request, a new session will be given to them. Calling Clear first also will cause problems if you wanted to access any session variables in the Session_End() event of the Global.Asax (they won't be there because you cleared them).Adenitis
@Adenitis actually I disagree. Session.Abandon(). gives the client a new session id. Session.clear clears out all the info on the server about the session so no other users can.I agree with NRCPerjure
@ Micah Armantrout I am not following your logic. Why clear out a session with Session.Clear(), then call Session.Abandon() which not only clears out the session, but also completely deallocates it? Also Session.Abandon() does not give the client a new session id. A subsequent request will, but not the fulfillment of the request that called Session.Abandon().Adenitis
If you use just Session.Abandon, other remaining logic in the ASP.NET pipeline can still access the current session values.Snotty
R
7

this code works and dont throw any exception:

Session.Abandon();  
Session["tempKey1"] = "tempValue1";

It's because when the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.

For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.

<% 
  Session.Abandon  
  Session("MyName") = "Mary" 
  Reponse.Write(Session("MyName")) 
%>

If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.

from MSDN Session.Abandon

Rajah answered 23/12, 2014 at 10:58 Comment(0)
F
4
Session.Abandon() 

will destroy/kill the entire session.

Session.Clear()

removes/clears the session data (i.e. the keys and values from the current session) but the session will be alive.

Compare to Session.Abandon() method, Session.Clear() doesn't create the new session, it just make all variables in the session to NULL.

Session ID will remain same in both the cases, as long as the browser is not closed.

Session.RemoveAll()

It removes all keys and values from the session-state collection.

Session.Remove()

It deletes an item from the session-state collection.

Session.RemoveAt()

It deletes an item at a specified index from the session-state collection.

Session.TimeOut()

This property specifies the time-out period assigned to the Session object for the application. (the time will be specified in minutes).

If the user does not refresh or request a page within the time-out period, then the session ends.

Flypaper answered 27/9, 2016 at 11:11 Comment(1)
your answer is clear and explains everything .... thnxFidelis
M
3

Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.

Maleficent answered 24/9, 2009 at 8:46 Comment(5)
thanks but this works:(inconsistent with your idea) Session.Abandon(); Session["tempKey1"] = "tempValue1"; Response.Write(Session["tempKey1"].ToString());Schaeffer
It does because session will be destroyed after you refresh your page actually. Session id it (usually) stored in a cookie.Maleficent
i dont understand. i mean after i call Session.Abandon() still i can add values to it. (even if page is posted back and again renders).Schaeffer
You may have you session set to autoregenerate id after it was destroyed. So when you assign a value to destroyed session new session will be generated automatically.Maleficent
yes, using this session id will regenerate but my question is: what is different between session.clear() and session.abandone() at all. in this way when autoregenerate is seted to false these tow dont differ in anything else raising Sesion_End?Schaeffer
L
3

clear-its remove key or values from session state collection..

abandon-its remove or deleted session objects from session..

Legitimize answered 25/9, 2009 at 10:47 Comment(0)
P
0

Existence of sessionid can cause the session fixation attack that is one of the point in PCI compliance. To remove the sessionid and overcome the session fixation attack, read this solution - How to avoid the Session fixation vulnerability in ASP.NET?.

Parrot answered 9/6, 2011 at 6:2 Comment(0)
K
0

I think it would be handy to use Session.Clear() rather than using Session.Abandon().

Because the values still exist in session after calling later but are removed after calling the former.

Kerbela answered 26/3, 2012 at 14:5 Comment(0)
P
0
this code works and dont throw any exception:

Session.Abandon();  
Session["tempKey1"] = "tempValue1";

One thing to note here that Session.Clear remove items immediately but Session.Abandon marks the session to be abandoned at the end of the current request. That simply means that suppose you tried to access value in code just after the session.abandon command was executed, it will be still there. So do not get confused if your code is just not working even after issuing session.abandon command and immediately doing some logic with the session.

Pluck answered 5/12, 2016 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.