Get Session Value in a Static Method

We cannot use session in a static method. So I will show one way in which this can be done without much hassle.
Just use the below syntax:

HttpContext.Current.Session["SessionName"].ToString();

Using this code we can access the session value in static methods too.

Create a website. Add a webform to it. Write the below code in the aspx page.

  1. <form id="form1" runat="server">  
  2.     <div>  
  3.         <asp:Label ID="LblName" runat="server"></asp:Label>  
  4.     </div>  
  5. </form>  
We have a label on the page. We will assign a name to it using session in a static method. In the code behind file write the following syntax.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Session["UserName"] = "DotNet Snippets!!";  
  4.   
  5.     LblName.Text = AssignSession();  
  6. }  
  7.   
  8. protected static string AssignSession()  
  9. {  
  10.     string _users = string.Empty;  
  11.   
  12.     _users = HttpContext.Current.Session["UserName"].ToString();  
  13.   
  14.     return _users;  
  15. }  
We will now run the code and see what output we get.

output
We get the value from the session in the label that is displayed on the webpage. I hope this is useful to the beginners.

 

Ebook Download
View all
Learn
View all