我正在编写一个asp.net MVC 2.0应用程序,我需要在用户登录后获取用户名并将其传递给其他函数。我尝试通过简单地修改AccountController的标准LogOn方法,这是我的代码:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
using (ShopController newCtrl = new ShopController())
{
if (Session["TempCart"] != null)
{
newCtrl.CreateShoppingCartFromSession((Cart)Session["TempCart"], User.Identity.Name);
}
}
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
问题是即使用户成功登录,“User.Identity.Name”仍为空白,我不知道为什么......
非常感谢任何帮助。
答案 0 :(得分:6)
表单身份验证方法设置一个身份验证cookie,该cookie在下一个请求中首次被读取和处理,因此User.Identity
仅在下一个请求时可用。
在此方法中,您必须先进行重定向或使用model.UserName
。