Get Session Value In A Static Method

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.   
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="form1" runat="server">  
  11.             <div>  
  12.                 <asp:Label ID="lblsessionName" runat="server"></asp:Label>  
  13.             </div>  
  14.         </form>  
  15.     </body>  
  16.   
  17.     </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

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now