我试图从会话UserId中获取当前用户,但出现此错误。 “无法将类型为'System.Int32'的对象转换为类型为'Trinity.Models.tblUser'。”
我在哪里创建会话ID:
[HttpPost]
public ActionResult Authorise(tblUser user)
{
using (var db = new TrinityEntities())
{
var userEmail = db.tblUsers.FirstOrDefault(x => x.Email == user.Email);
var userPassword = db.tblUsers.FirstOrDefault(y => y.Password == user.Password);
//check login incorrect
if (userEmail == null || userPassword == null)
{
ViewBag.LoginIncorrect = "E-mail or Password not correct";
return View("Index", user);
}
else
{
Session["UserID"] = userEmail.Id;
return RedirectToAction("Index", "Home");
}
}
}
出现错误的地方:
public ActionResult Index()
{
if (Session["UserID"] == null)
{
return Redirect("/");
}
var currentUser = (Models.tblUser) Session["UserID"];
using (var db = new Models.ChatContext())
{
ViewBag.allUsers = db.Users.Where(u => u.FirstName != currentUser.FirstName).ToList();
}
ViewBag.currentUser = currentUser;
return View();
}
答案 0 :(得分:1)
您只存储ID(一个数字),但是当您读回ID时,您会期望整个用户都无法使用。相反,您需要使用ID重新加载用户:
var currentUserId = Session["UserID"];
var user = db.tblUsers.FirstOrDefault(x => x.Id == currentUserId);