asp.net-core - 调用操作时,会话被清除.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。我究竟做错了什么?
解决方案
确保在中间件管道中添加并使用它session
:service collection
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app)
{
app.UseSession();
}
Microsoft 文档中的更多信息:ASP.NET Core 中的会话和状态管理
推荐阅读
- java - java中的同步
- node.js - 我无法在 Windows 10 中安装 Angular-cli
- javascript - 字符串到 React 组件
- plesk - is_executable(): open_basedir 限制在 plesk 服务器中生效
- php - 获取一个州的所有城市
- xml - 为 uri 编码和绝对 Windows 路径
- javascript - Webforms:submitdisabledcontrols=true 使某些控件保持禁用状态
- javascript - 如何通过 $http POST 发送数组数据并在 PHP 中解析相同的数据?
- elasticsearch - 我们可以限制数量吗?在弹性搜索中链接到别名的索引
- c# - 无法创建多个 ID,但我只有一个