Home > Software engineering >  How to use Session in .net core?
How to use Session in .net core?

Time:04-04

How to use Session in dot net core ?

I wanted to use session tag to store the user id and username when a user is logged in. I am using .net core version 3.1 I have created an Account Controller and in the Login(Post Method) I am trying to use session tag. Here is the Login Method in AccountController.cs

 //POST Login
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Login(Account user)
        {
            if(ModelState.IsValid)
            {
                var obj = _db.Accounts.Where(u => u.Name.Equals(user.Name) && u.Password.Equals(user.Password)).FirstOrDefault();
                if(obj != null)
                {
                    Session["Id"] = obj.Id.ToString(); // Error : The name 'Session' does not exist in the current context
                    Session["Name"] = obj.Name.ToString(); // Error : The name 'Session' does not exist in the current context
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(user);
        }

I have also used services.AddSession() in ConfigureServices and app.UseSession() in Configure in Startup.cs file Configure Services in Startup.cs

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
            );

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

        }

Configure in Startup.cs

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();
            }

    
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            //app.UseAuthentication();

            app.UseAuthorization();
            app.UseSession();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

How do I fix this issue?

CodePudding user response:

You could use something like this:

if(obj != null)
{

   const string userId = "_UserId";
   const string userName = "_UserName";

   HttpContext.Session.SetString(userId, obj.Id.ToString());
   HttpContext.Session.SetString(userName, obj.Name.ToString());

   return RedirectToAction("Index", "Home");

}

You can use this to get it:

const string userId = "_UserId";
const string userName = "_UserName";

string user = httpContext.Session.GetString(userId);
string name = httpContext.Session.GetString(userName);

Edit #1: TY @Dharman. (copy/pasted TS with tabs/spaces)

CodePudding user response:

To setup your Session in .NET CORE, you can refer to this S.O answer. Now regarding your question on clearing the Session, you can do this:

HttpContext.Session.Clear();

You can read more on the MSDN

  • Related