How to access Session variables in any Class?

 Posted by vishalneeraj-24503 on 12/27/2013 | Category: ASP.NET Interview questions | Views: 1178 | Points: 40
Answer:

We use System.Web.HttpContext.Current class to access Session in any class

like

String user_name = Convert.ToString(System.Web.
HttpContext.Current.Session["User_Name"]);

The reason you can call Session in your code-behind is because ASP.Net pages by default extend the System.Web.UI.Page type. This has a Session public property. If you look at the code for this in Reflector you can see that it just calls HttpContext.Current.Session itself (through its own Context property).

In other classes you will not have access to that property, but you can use HttpContext.Current.Session to access the session data instead, as long as you're running in the context of a web application.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response