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