4

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.

Xaxum
  • 3,545
  • 9
  • 46
  • 66

1 Answers1

5

There lies the answer to your question in title:

When is HttpContext.User.Identity set?

Hope this helps

Community
  • 1
  • 1
Display Name
  • 4,672
  • 1
  • 33
  • 43
  • Thanks for the link. So apparently this is not available until after the request for the next page if I am understanding this correctly. I guess I will have to continue to use what is working. – Xaxum Sep 26 '12 at 20:31