0

I've added a few new columns to User model which inherited from IdentityUser:

public class ApplicationUser : IdentityUser
{

    public int Age { get; set; }
    public bool Sex { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        //userIdentity.AddClaim(new Claim("age", this.Age.ToString()));

        return userIdentity;
    }

}

By default I can only get user name, like shown in _LoginPartial.cshtml:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

I'd like get custom info from User.Identity like Age and Sex, for example. I find the solutions around pretty weird to implement and using claim I couldn't make it global once I'm gonna display it in every page.

If the way to do it is by adding claims like this:

userIdentity.AddClaim(new Claim("age", this.Age.ToString()));

How can I get it easily in a View?

  • This may be of help [Custom Identity & Principal](http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal) – Eckert May 21 '15 at 13:17

2 Answers2

0

I find it easier to user session cookies, so in AccountController.cs I add two lines in the case SignInStatus.Success:

var user = SignInManager.UserManager.FindByEmail(model.Email);
Session["userInfo"] = user.Age;

Then I can call in the _LoginPartial.cshtml for example:

 @{
    if (Session["userInfo"] != null)
    {
        var age = Session["userInfo"];
        <li>@Html.ActionLink("Age: " + age.ToString(), "Index", "Albums")</li>
    }
}
0

This pulls from WebpageRenderingBase, which has an IPrincipal User property.

IPrincipal defines an Identity property which gives access to an item which is of a type that implements the interface IIdentity.

So, what you'd be hoping is that the @User.Identity IIndentity returned might actually be an ApplicationUser, and if it is, then you could cast it to such and then access the additional properties.

If that is true, then you're already done. If it's not, then you'll need to first obtain an ApplicationUser by some other means.

So the big question is: What actual type is the item which implements the IIdentity interface, for which you already have?

@if( User.Identity is ApplicationUser)
{
  <text>
    @(((ApplicationUser)User.Identity).Age)
  </text>
}
else 
{
  //GoFish
}
Greg
  • 2,410
  • 21
  • 26