How to Access Session Variables from Any Class in ASP.NET

How to access session variables from any class in ASP.NET?

(Updated for completeness)

You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].

But please read on for my original answer...


I always use a wrapper class around the ASP.NET session to simplify access to session variables:

public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}

// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}

// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}

This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:

int loginId = MySession.Current.LoginId;

string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;

DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;

This approach has several advantages:

  • it saves you from a lot of type-casting
  • you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
  • you can document your session items by adding XML doc comments on the properties of MySession
  • you can initialize your session variables with default values (e.g. assuring they are not null)

Accessing Session in Class File

Thanks all for the help. You helped me track down the answer. Here is the solution I needed:

How to access Session in .ashx file?

Access session variables across all controllers in .net core 5.0

Looks like your re-creating the authentication system in ASP.NET

I would very much suggest that you consider using the Cookie Authentication system that's already build in. This does NOT require you to use ASP.NET Identity.

See https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0

In your startup file you would have to set

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.AccessDeniedPath = "/Forbidden/";
});

Then in your ProfileController you can run the below code to set the authentication cookie.

var claimsIdentity = new ClaimsIdentity(new List<Claim>
{
new Claim("SessionUserToken", account.data)
}, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
new AuthenticationProperties());

Then you can validate access either using the classic attributes like [Authorize] or you can check User.Identity.IsAuthenicated and when you need the SessionUserToken you can access User.FindFirstValue("SessionUserToken")

How to access session in class library .Net Core 5

As @King King answered, you could inject the IHttpContextAccessor into the class.

Step 1 Add Session service

    public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();

services.AddSession();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{
...
app.UseAuthorization();

app.UseSession();

app.UseEndpoints(endpoints =>
...
}

Step 2 Access Session in custom class

public class SessionTest
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;

public SessionTest(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public void setSession()
{
_session.SetString("Test", "Hello World!");
}

public void getSession()
{
var message = _session.GetString("Test");
...
}
}

Step 3 access session via custom class

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _session;

public HomeController(IHttpContextAccessor httpContextAccessor,ILogger<HomeController> logger)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
_session = _httpContextAccessor.HttpContext.Session;
}

public IActionResult Index()
{
SessionTest session = new SessionTest(_httpContextAccessor);
session.setSession();
session.getSession();
return View();
}
}

How can I access Session vars from Base class in ASP.Net?

Just curious why are you saving this in the base page constructor?

You shouldn't be accessing the session from the constructor but the Page_Init instead. See the following post:

http://weblogs.asp.net/anasghanem/archive/2008/05/07/avoid-using-the-session-in-the-page-constructor.aspx

The session variable will be accessible at any time when implementing the page functionality so why not create a static class / method with functionality to grab all your session data? I don't see why you would want to duplicate storage of this data in your base class.

You might want to check out this thread:
ASP.Net Session



Related Topics



Leave a reply



Submit