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. LblName.Text = AssignSession();
  5. }
  6. protected static string AssignSession()
  7. {
  8. string _users = string.Empty;
  9. _users = HttpContext.Current.Session["UserName"].ToString();
  10. return _users;
  11. }
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.