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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With