views:

18

answers:

1

Hi,

I am writing an asp.net MVC 2.0 application, and I need to get username after the user logs in and pass it to other function. I tried that by simply modifying the standard LogOn method for AccountController, here is my code:

[HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(model.UserName, model.Password))
            {

                FormsService.SignIn(model.UserName, model.RememberMe);
                using (ShopController newCtrl = new ShopController())
                {
                    if (Session["TempCart"] != null)
                    {

                        newCtrl.CreateShoppingCartFromSession((Cart)Session["TempCart"], User.Identity.Name);
                    }
                }
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

The problem is that even though the user is logged in successfully, the "User.Identity.Name" is blank, and I don't know why...

Any help would be much appreciated.

+2  A: 

Forms authentication methods set an authentication cookie which gets read and processed for the first time on the next request, thus the User.Identity becomes available only from the next request.

In this method you will either have to do a redirect first or use your model.UserName.

Jappie

related questions