登录时存储用户数据

时间:2014-07-23 20:17:28

标签: asp.net-mvc-4

我是C#和ASP.NET的新手,所以请耐心等待。

我正在制作一个消耗2种不同Web服务的网站,希望能够为每个系统使用用户的个人帐户/ api密钥。当用户在我的系统上创建帐户时,我会获取此信息。我想在用户登录后立即从数据库中检索此信息,并将其存储在Session中,以便每次我的网站调用其中一个API时都可以使用它。

我试过了:

public ActionResult Login(LoginModel model, string returnUrl)
{
  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
  {
     SiteEntities SiteDB = new SiteEntities();
     Session["user"] = SiteDB.T_USER.Find(WebSecurity.CurrentUserId);
     return RedirectToLocal(returnUrl);
  }

  // If we got this far, something failed, redisplay form
  //ModelState.AddModelError("", "The user name or password provided is incorrect.");
  ViewBag.WarningMessage = "The user name or password provided is incorrect.";
  return View(model);
}

但是,显然这不起作用,因为此时尚未设置WebSecurity.CurrentUserId。

我的问题是,如果我想尽早获取用户的数据,以便用户可以进行整个访问,我应该在哪里检索它?

1 个答案:

答案 0 :(得分:0)

我建议使用用户名来查找详细信息而不是UserId,因此您的代码应如下所示

public ActionResult Login(LoginModel model, string returnUrl)
{
  if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
  {
     SiteEntities SiteDB = new SiteEntities();
     // ------- updated the below line to use username -------------------------------
     Session["user"] = SiteDB.T_USER.Find(model.UserName);
     return RedirectToLocal(returnUrl);
  }

  // If we got this far, something failed, redisplay form
  //ModelState.AddModelError("", "The user name or password provided is incorrect.");
  ViewBag.WarningMessage = "The user name or password provided is incorrect.";
  return View(model);
}
相关问题