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

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. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>  
  2.     <!DOCTYPE html>  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:Label ID="lblsessionName" runat="server"></asp:Label>  
  13.             </div>  
  14.         </form>  
  15.     </body>  
  16.   
  17.     </html>  
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. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. namespace WebApplication1 {  
  8.     public partial class WebForm1: System.Web.UI.Page {  
  9.         protected void Page_Load(object sender, EventArgs e) {  
  10.             Session["UserName"] = "Soumalya Das";  
  11.             lblsessionName.Text = AssignSession();  
  12.         }  
  13.         protected static string AssignSession() {  
  14.             string _users = string.Empty;  
  15.             _users = HttpContext.Current.Session["UserName"].ToString();  
  16.             return _users;  
  17.         }  
  18.     }  
  19. }