Add user First Name and Last Name to an ASP.NET Identity 2?

后端 未结 2 1166
别跟我提以往
别跟我提以往 2020-12-31 04:05

I changed over to use the new ASP.NET Identity 2. I\'m actually using the Microsoft ASP.NET Identity Samples 2.0.0-beta2.

Can anyone tell me where and how I can mo

相关标签:
2条回答
  • 2020-12-31 04:42

    I realize this post is a few years old, but with ASP.NET Core gaining traction I ended up here having a similar question. The accepted answer recommends you update your user data model to capture this data. I don't think that it's a bad recommendation, but from my research claims is the correct way to store this data. See What is the claims in ASP .NET Identity and User.Identity.Name full name mvc5. The latter is answered by someone from the ASP.NET Identity team at Microsoft.

    Here is a simple code sample showing how you add those claims using ASP.NET Identity:

    var claimsToAdd = new List<Claim>() {
        new Claim(ClaimTypes.GivenName, firstName),
        new Claim(ClaimTypes.Surname, lastName)
    };
    
    var addClaimsResult = await _userManager.AddClaimsAsync(user, claimsToAdd);
    
    0 讨论(0)
  • 2020-12-31 04:59

    You'll need to add it to your ApplicationUser class so if you use Identity Samples, I imagine you have something like that in your IdentityModels.cs

    public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
    

    after adding First and Last Names it would look like this:

    public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    

    Then when you register user, you need to add them to the list now that they are defined in ApplicationUser class

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = "Jack", LastName = "Daniels" };
    

    first and last names will end up in AspNetUsers table after you do the migrations

    0 讨论(0)
提交回复
热议问题