Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of the logged in user in asp.net mvc 4

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?

like image 760
Shihan Khan Avatar asked Jan 27 '26 14:01

Shihan Khan


1 Answers

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.

like image 57
dlght Avatar answered Jan 30 '26 02:01

dlght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!