Get and Set Session in AspNetCore and MVC Core

In this example i am using the MVC Core 3.0 to introduce how to GET and SET Session

1. Install Microsoft.AspNetCore.Session

Add Session Microsoft.AspNetCore.Session using Nuget


2. In Startup.cs



 public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddControllersWithViews();
            // Add MVC services to the services container.
            services.AddMvc();            
            services.AddSession();
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //IMPORTANT: This session call MUST go before UseMvc()
            app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization(); 
            app.UseEndpoints(endpoints =>
            {                
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

3. Add class SessionExtensions with function SetString, SetObjectAsJson and GetObjectFromJson


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

        public static void SetSessionString(this ISession session, string key, object value)
        {
            session.SetString(key, value);
        }

        public static T GetObjectFromJson(this ISession session, string key)
        {
            var value = session.GetString(key);

            return value == null ? default(T) : JsonConvert.DeserializeObject(value);
        }
    }

4. Use the Session
 HttpContext.Session.SetObjectAsJson("UserInfo", customer); //customer is object
 HttpContext.Session.SetSessionString("Username", customer.Username);
And code when get string or Object
 GetString
Context.Session.GetString("Username") 
GetObjectFromJson
HttpContext.Session.GetObjectFromJson("UserInfo");
Reactions

Post a Comment

0 Comments