如何解决调用 .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
页面时,会话变量不再保持值。它们都返回空值。我做错了什么?
解决方法
确保将 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。