Sessions in .Net Core

Sessions will not work out of the box, you need to do some setup:

  1. Add the nuget package Microsoft.AspNetCore.Session

  2. In Startup.cs add to ConfigureServices

    1
    2
    3
    services.AddSession(options => {
    options.IdleTimeout = TimeSpan.FromMinutes(15);
    });
  3. In Startup.cs add to Configure

    1
    app.UseSession();
  4. Then in your controllers you can get and set values, would be best to have ProjectName set in a constants file.

    1
    2
    3
    HttpContext.Session.SetString("ProjectName", project.ProjectName);

    var projectName = HttpContext.Session.GetString("ProjectName");

Microsoft.AspNetCore.Http

These are the methods available for use in the controller (Version=2.2.0.0)

1
2
3
4
5
public static byte[] Get(this ISession session, string key);
public static int? GetInt32(this ISession session, string key);
public static string GetString(this ISession session, string key);
public static void SetInt32(this ISession session, string key, int value);
public static void SetString(this ISession session, string key, string value);

References