获取asp.net mvc 4中登录用户的id
本文关键字:登录 用户 id asp net mvc 获取 | 更新日期: 2023-09-27 18:15:51
我使用asp.net SimpleMembership
。我试图在ViewBag
中显示登录用户的id。出于某种原因,我得到NULL为ProvidedUserKey()
。这是我的代码,
[HttpPost]
public ActionResult Login(ClientReg user)
{
if (ModelState.IsValid)
{
FormsAuthentication.SetAuthCookie(user.username, false);
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Login");
}
}
[Authorize]
public ActionResult Index()
{
string userId = Membership.GetUser().ProviderUserKey.ToString(); //Null error in this line
ViewBag.UserId = userId;
return View();
}
<<p> 视图/strong> <div class="container">
@ViewBag.UserId
</div>
如何获取登录用户的id ?
使用这个类代替Membership:
WebSecurity.GetUserId(User.Identity.Name);
Simple Membership继承了WebSecurity实例,是更可靠的获取用户数据的方法。
object id = Membership.GetUser().ProviderUserKey