首页 > 解决方案 > 调用操作时,会话被清除.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页面时,会话变量不再具有值。他们都返回null。我究竟做错了什么?

标签: asp.net-core.net-coresession-cookies

解决方案


确保在中间件管道中添加并使用它sessionservice collection

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

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

Microsoft 文档中的更多信息:ASP.NET Core 中的会话和状态管理


推荐阅读