1

I am using SimpleMembership in my ASP.NET MVC 4 Project. After I login, I am unable to get the current UserName and the current UserId, here is my Login function:

[HttpPost]
        public ActionResult Login(FormCollection form)
        {
            bool success = WebSecurity.Login(form["username"], form["password"], false);
            if (success)
            {
                string returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl == null)
                {
                    Response.Redirect("~/home/index?userId=" + WebSecurity.CurrentUserId + "&userName=" + WebSecurity.currentUserName);
                }
                else
                {
                    Response.Redirect(returnUrl);
                }
            }
            return View();
        }

On this line Response.Redirect("~/home/index?userId=" + WebSecurity.CurrentUserId + "&userName=" + WebSecurity.currentUserName); WebSecurity.CurrentUserId returns -1 and WebSecurity.currentUserName returns ""

Am I missing something? Any help would be much appreciated.

However in my View if I do this @{ int value; value = WebSecurity.currentUserID; } @{ ViewBag.Title = value; } the title in my browser is the correct currentUserId

user3723240
  • 395
  • 3
  • 11
  • 29

2 Answers2

1

MSDN:

When a user is logged in, ASP.NET sets an authentication token in a cookie that lets ASP.NET know on subsequent requests that the user has been logged in. If persistCookie is false, the token is valid only until the user closes the browser.

So it can only be used on requests after your login. Use:

WebSecurity.GetUserId(username);
Moe Bataineh
  • 1,032
  • 1
  • 12
  • 29
1

try this

[HttpPost]
            public ActionResult Login(FormCollection form)
            {
                bool success = WebSecurity.Login(form["username"], form["password"], false);
                if (success)
                {
                    var userId = WebSecurity.GetUserId(form["username"]);
                    string returnUrl = Request.QueryString["ReturnUrl"];
                    if (returnUrl == null)
                    {
                        Response.Redirect("~/home/index?userId=" + userId + "&userName=" + WebSecurity.currentUserName);
                    }
                    else
                    {
                        Response.Redirect(returnUrl);
                    }
                }
                return View();
            }

WebSecurity will not internalize until the redirect is complete (by design). A way around it is to get the userID via username on successful login

PaulBinder
  • 2,022
  • 1
  • 16
  • 26