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>
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.
- 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 will now run the code and see what output we get.
We get the value from the session in the label that is displayed on the webpage. I hope this is useful to the beginners.