Store and Read Objects from Session in ASP.NET Core

Here you go;

In your Startup.cs, under the Configure method, add the following line:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}

And under the ConfigureServices method, add the following line:

public void ConfigureServices(IServiceCollection services)
{
  //Added for session state
  services.AddDistributedMemoryCache();

  services.AddSession(options =>
  {
  options.IdleTimeout = TimeSpan.FromMinutes(10);               
  });
}

The simple method to store and read data from session is;

# In a class;
Session.SetString("Email", "foo.com"); //store data
Session.GetString("Email"); //read data

# In Razor pages
@using Microsoft.AspNetCore.Http; 
string CustomerEmail = String.Empty;
@if (Context.Session.GetString("Email") != null)
 {
     CustomerEmail = Context.Session.GetString("Email").ToString();
 }
}

# You can use it in Razor markup 
<ul class="navbar-nav mr-auto float-right">
   <li class="nav-item">
      <span class="navbar-text text-light">Hello @CustomerEmail</span>
   </li>

</ul>

In order to store complex objects in your session in .NET Core, follow the following steps:

Create a model class of your object type (in your case EmployeeDetails):

public class EmployeeDetails
{
    public string EmployeeId { get; set; }
    public string DesignationId { get; set; }
}

Then create a SessionExtension helper to set and retrieve your complex object as JSON:

public static class SessionExtensions
{
  public static void SetObjectAsJson(this ISession session, string key, object value)
   {
     session.SetString(key, JsonConvert.SerializeObject(value));
   }

   public static T GetObjectFromJson<T>(this ISession session, string key)
   {
     var value = session.GetString(key);
     return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
   }
}

Then finally set the complex object in your session as:

var employee = new EmployeeDetails();
employee.EmployeeId = "1";
employee.DesignationId = "2";

HttpContext.Session.SetObjectAsJson("EmployeeDetails", employee);

To retrieve your complex object in your session:

var employeeDetails = HttpContext.Session.GetObjectFromJson<EmployeeDetails>("EmployeeDetails");
int employeeID = Convert.ToInt32(employeeDetails.EmployeeId);
int designationID= Convert.ToInt32(employeeDetails.DesignationId);

My session was not working. it turns out that it relates to GDPR issues. Three fixes;

FIX-I

The first fix is to provide user a login page and let him accept cookies policy.

If you don’t provide a login page and still want to configure sessions in ASP.NET Core, you need these two fixes in Startup.cs file;

Fix-II Startup.cs file ConfigureServices method. Add this line;

 services.AddSession(options =>
 {
    options.Cookie.IsEssential = true;
 });

Fix-III Startup.cs file Configure method, comment this line;

//app.UseCookiePolicy();

The most common fix is FIX-I. For testing I choose Fix-II and session started working.

Sources

https://andrewlock.net/session-state-gdpr-and-non-essential-cookies/

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect