调用 .Net Core 时会话被清除

Session gets cleared when actions are called .Net Core

我在用户登录时设置会话变量。

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

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

当他们想要更新个人资料时,我使用该信息 运行 Sql 进行查询。 Myprofile 页面提取他们的信息并将它们放入文本框中。

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

当他们提交更改时,它会更新数据库。现在我注意到,当我返回 Dashboard 页面时,会话变量不再保持值。他们都 return null。我做错了什么?

确保将 session 添加到 service collection 并在中间件管道中使用它:

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

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
}

Microsoft 文档中的更多信息:Session and state management in ASP.NET Core