Xaxum
Xaxum

Reputation: 3675

When does User.Identity.Name get set in MVC4

I am trying to get a custom property out of the UserProfile in MVC4 which uses SimpleMembershipProvider. My table is as follows:

 public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }

        //Added to round out requirements for site user profile
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Site { get; set; }
    }

When I try to get the userprofile item I am interested in, FirstName, in a session variable on login

public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                var context = new UsersContext();
                var curuser = context.UserProfiles.First(p => p.UserName == User.Identity.Name);
                Session["FName"] = curuser.FirstName;

                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

I get an error: Sequence contains no elements referring to my var curuser line. If I replace User.Identity.Name with model.Username it works fine. I would rather use User.Identity.Name since I can use this wherever needed, or so I thought.

Upvotes: 4

Views: 23591

Answers (1)

Display Name
Display Name

Reputation: 4732

There lies the answer to your question in title:

When is HttpContext.User.Identity set?

Hope this helps

Upvotes: 5

Related Questions