0

So my users should still login using their email adress, but I want my top menu to greet them by their Name. I have the name implemented and everything, I just need a way of getting it to show.

Currently I have this in my top menu.

Logged in as @User.Identity.Name

This gives me AppUser.EmailAddress, but i need the AppUser.Name

This is my Login action, currently it only contains data from the loginviewmodel (email, password, rememberme).

public async Task<IActionResult> Login(LoginViewModel login, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return View(login);
            }

        var result = await _signInManager.PasswordSignInAsync(
            login.EmailAddress,
            login.Password,
            login.RememberMe, false);

        if (!result.Succeeded)
        {
            ViewBag.Succeeded = false;

            return View(login);
        }

        if (string.IsNullOrWhiteSpace(returnUrl))
        {
            return RedirectToAction("Index", "Home");
        }
        return Redirect(returnUrl);

The name exists in my AppUser class and my RegisterViewModel which is used by the register action.

I'm using Identity 3.0.0 but I welcome ways of solving it on other versions,

user3621898
  • 589
  • 5
  • 24
  • Load their name using the email address from the database and display that – CRice Dec 06 '15 at 23:00
  • 4
    Don't hit the database - ASP.NET Identity uses claims, and there is a specific claim type for a GivenName and Surname. When the user logs on, set these claim values and use an extension method to display the value. See my answer here for details: http://stackoverflow.com/questions/31974228/can-you-extend-httpcontext-current-user-identity-properties/31976327#31976327 – Brendan Green Dec 07 '15 at 01:59
  • Thanks, I'll check it out once I find the time. – user3621898 Dec 07 '15 at 11:31
  • Usermanager doesnt have the CreateIdentityAsync method anymore, nor can I find DefaultAuthenticationTypes in Identity 3.0.0 – user3621898 Dec 07 '15 at 12:00

1 Answers1

0

Try this:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

Then you have user which you could use it like:

Var username=user.lastname;
Hadee
  • 1,392
  • 1
  • 14
  • 25
  • 2
    Don't do this - you will uneccessarily hit the db on every request to get the user name. Since you're using Asp.net Identity, set the users name in a claim – Brendan Green Dec 07 '15 at 01:26