Search code examples
asp.net-core.net-coresession-cookies

Session gets cleared when actions are called .Net Core


I set session variables when the user signs in.

HttpContext.Session.SetInt32("UserID", Logininformation.UserID);
                    HttpContext.Session.SetString("UserName", Logininformation.UserPersonsName);

                    return RedirectToAction("Userpanel", "Dashboard");

I use that info to run Sql queries when they want to update their profile. Myprofile page pulls out their info and puts them in textboxes.

public IActionResult Myprofile()
    {
        Myprofileinfo myprofileinfo = new Myprofileinfo();
        myprofileinfo.Userid = HttpContext.Session.GetInt32("UserID");

        SqlConnection sqlcon = new SqlConnection("my connection string");
        sqlcon.Open();
        SqlCommand sqlcom = new SqlCommand("select * from users where userid="+HttpContext.Session.GetInt32("UserID"), sqlcon);
        SqlDataReader reader= sqlcom.ExecuteReader();
        reader.Read();
        myprofileinfo.Userusername = reader[1].ToString();
        myprofileinfo.Userpassword = reader[2].ToString();
        myprofileinfo.UserName = reader[3].ToString();
        myprofileinfo.Userlastname = reader[4].ToString();
        myprofileinfo.Userauthority = reader[6].ToString();
        sqlcon.Close();
        return View(myprofileinfo);
    }

when they submit the changes, it will update the database. now what i have noticed is when i go back to the Dashboard page, the session variables no longer hold value. they all return null. what am i doing wrong?


Solution

  • Make sure you add session to service collection and use it in middleware pipelines :

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();
        services.AddSession();
    }
    
    public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
    }
    

    More info in Microsoft docs : Session and state management in ASP.NET Core