3

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?

James
  • 20,957
  • 5
  • 26
  • 41
Shihan Khan
  • 2,180
  • 4
  • 34
  • 67
  • how are you authenticating the user? did you also see this: http://stackoverflow.com/questions/7146830/membership-getuser-provideruserkey-always-returns-null – Ahmed ilyas Oct 04 '15 at 14:32
  • yes, I did checked this post before. But I can't understand it's explanation. – Shihan Khan Oct 04 '15 at 14:37
  • ensure that the user is actually authenticated....I don't really see any authentication code except for setting a cookie value which is not really truly authenticating the user – Ahmed ilyas Oct 04 '15 at 14:51
  • I've provided a short version of my full code. In full, I've ensured that user is 100% authenticated & I can only fetch his username, but I also want to fetch his other infos from db. Any idea how can I do it? – Shihan Khan Oct 04 '15 at 14:55

2 Answers2

2

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.

dlght
  • 1,406
  • 1
  • 18
  • 35
-1
object id = Membership.GetUser().ProviderUserKey