当用户登录时,我设置会话变量。
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。我做错了什么?
确保将session
添加到service collection
并在中间件管道中使用:
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app)
{
app.UseSession();
}
Microsoft文档中的更多信息:ASP.NET Core 中的会话和状态管理