Best way to end user session in asp.net

September 11, 2008 20:11 by pradeep.mishra

Session is very important state management tool in asp.net. You fill in this object with lots of user specific information when user requests a certain page e.g. Logged in user information like name, emailId etc can be stored after the sucessfull login. However for better performance we must make sure that all the objects are removed from the session when we don't need them. So question arises what's the best way to end user's session in case user logs out. Session object have two method implemented to straight away clear all the objects in session. those are...

 Session.Clear(), Session.RemoveAll()

 Eventually these two methods are serving the same purpose but I am still not able to figure out what's the difference between the two. Seems there is some legecy code left by microsoft developers :-). If you know the difference do let me know.

There is one other method called Abandon() which must be used in case user logs out. Abondon method marks the current session for deletion as soon as user moves to next page. So it is always good to use Session.Abandon() in the logout event. In this way the same session object can not be reused in subsequent request. Let's take an example

   1:   
   2:  Session["UserId"] = "user@noesispedia.com"
   3:  Session.Abandon()
   4:  Response.Write((string)Session["UserId"] )

Session is still accesible in this page however if you try to acess userId in next page it won't be available.

One more point I would like to make here i.e. Session_Start event will be raised in case session is abandoned however if you don't call abandon method and just use Clear() session object won't be destroyed even after logout and Session_Start event will not be fired as session still exists in memory. To summarize use

   1:   
   2:  Session.Clear()
   3:  Session.Abandon() 
   4:  //Redirect to logout page. 

Hope this helps! kick it on DotNetKicks.com

Currently rated 4.3 by 6 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading