Reputation: 2188
I'm using asp.net SimpleMembership
. I'm trying to show the id of the logged-in user in a ViewBag
. For some reason I'm getting NULL for ProvidedUserKey()
. Here is my code,
Controller
[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();
}
View
<div class="container">
@ViewBag.UserId
</div>
How can I get the id of the logged-in user?
Upvotes: 3
Views: 1336
Reputation: 926
Use this class instead of Membership:
WebSecurity.GetUserId(User.Identity.Name);
Simple Membership inherits the WebSecurity instance and is more reliable way to get the data for the user.
Upvotes: 2