Click here to Skip to main content
13,593,913 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

11K views
1 bookmarked
Posted 1 Sep 2017
Licenced CPOL

ASP.NET Core 2.0 Session State

, 1 Sep 2017
Rate this:
Please Sign up or sign in to vote.
How to store data in session state using ASP.NET Core. Continue reading...

Problem

How to store data in session state using ASP.NET Core.

Solution

Using an empty project from a previous post, amend Startup class ConfigureServices() method, add services for session and its backing store:

 

public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession();
        }

Add the session middleware in Configure() method:

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

            app.Use(async (context, next) =>
            {
                context.Session.SetString("GreetingMessage", "Hello Session State");
                await next();
            });

            app.Run(async (context) =>
            {
                var message = context.Session.GetString("GreetingMessage");
                await context.Response.WriteAsync($"{message}");
            });
        }

Discussion

We can use session in order to share information between different HTTP requests coming from a single browser. The data is stored in a cache (IDistributedCache implementation to be specific) and accessed via HttpContext.Session property.

A cookie is stored in browser to correlated the HTTP requests. The default name of this cookie is .AspNet.Session.

During the configuration of session services, we can set various properties:

  • HttpOnly: Sets whether cookie is accessible through JavaScript. Default is true, which means it can’t be accessed via scripts on the client-side.
  • Name: Used to override the default cookie name.
  • SecurePolicy: Determines if session cookie is only transmitted via HTTPS requests.
  • IdleTimeout: Sets the time for session expiry, each request resets the timeout. Default is 20 minutes.
public void ConfigureServices(
           IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.Name = ".Fiver.Session";
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.IdleTimeout = TimeSpan.FromMinutes(10);
            });
        }

Storing Objects

HttpContext.Session (or ISession that it implements) does not provide a built-in way to store complex objects, however, we can serialize objects into JSON strings to achieve this:

public static class SessionExtensions
    {
        public static void SetObject<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

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

Now we can use these extension methods like below:

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

            app.Use(async (context, next) =>
            {
                context.Session.SetObject("CurrentUser",
                    new UserInfo { Username = "James", Email = "james@bond.com"  });
                await next();
            });

            app.Run(async (context) =>
            {
                var user = context.Session.GetObject<UserInfo>("CurrentUser");
                await context.Response.WriteAsync($"{user.Username}, {user.Email}");
            });
        }

Accessing via Dependency Injection

To access session using dependency injection, you could use IHttpContextAccessor (via constructor), which gives you access to HttpContext.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tahir Naushad
Software Developer (Senior)
United Kingdom United Kingdom
Qualified and skilled professional with experience working as a Software Developer, Technical Lead and Architect. I have worked on windows, web and distributed applications using the latest set of technologies within the Microsoft .NET ecosystem. I have lead teams using agile methodologies and trained developers in writing well-designed and maintainable software applications.

Currently focusing on C#, ASP.NET Core, EF, JavaScript, React, Azure, Domain Driven Design and Microservices.

You may also be interested in...

Comments and Discussions

 
QuestionNo service for type 'Microsoft.AspNetCore.Http.HttpContext' has been registered. sessions error Pin
David Alejandro Garcia Garcia10-May-18 6:13
memberDavid Alejandro Garcia Garcia10-May-18 6:13 
AnswerRe: No service for type 'Microsoft.AspNetCore.Http.HttpContext' has been registered. sessions error Pin
David Alejandro Garcia Garcia10-May-18 11:26
memberDavid Alejandro Garcia Garcia10-May-18 11:26 
QuestionSession Timeout Pin
Member 981250222-Nov-17 1:29
memberMember 981250222-Nov-17 1:29 
QuestionDoes not work across instances Pin
Nikodem Jaworski8-Nov-17 11:27
memberNikodem Jaworski8-Nov-17 11:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02-2016 | 2.8.180618.1 | Last Updated 1 Sep 2017
Article Copyright 2017 by Tahir Naushad
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid