We cannot use session in a static method. Thus, I will show one way in which this can be done without much hassle.

Just use the syntax, given below:.

syntax

Using this code, we can access the session value in the static methods too. Create a Website. Add a Webform to it. Write the code, given below, 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. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:Label ID="lblsessionName" runat="server"></asp:Label>
  11. </div>
  12. </form>
  13. </body>
  14. </html>
We have a label on the page. We will assign a name to it, using session in a static method. In the code at the backend file, write the syntax, given below:
  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. {
  9. public partial class WebForm1: System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. Session["UserName"] = "Soumalya Das";
  14. lblsessionName.Text = AssignSession();
  15. }
  16. protected static string AssignSession() {
  17. string _users = string.Empty;
  18. _users = HttpContext.Current.Session["UserName"].ToString();
  19. return _users;
  20. }
  21. }
  22. }
Output

Output