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.
- <form id="form1" runat="server">
- <div>
- <asp:Label ID="LblName" runat="server"></asp:Label>
- </div>
- </form>
- protected void Page_Load(object sender, EventArgs e)
- {
- Session["UserName"] = "DotNet Snippets!!";
- LblName.Text = AssignSession();
- }
- protected static string AssignSession()
- {
- string _users = string.Empty;
- _users = HttpContext.Current.Session["UserName"].ToString();
- return _users;
- }

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

Join the conversation! Your thoughts help the community grow.