What if you want to add additional parameter or field in the user identity table i.e. AspNetUser. We might need this one so lets look how we can achieve it.
public class ApplicationUser : IdentityUser { public string ContactName { get; set; } }
dotnet ef migrations add ContactNameField dotnet ef database update
Once done our database is updated with the new field added as ContactName
[Required] [Display(Name = "Name")] public string ContactName { get; set; }
<div class="form-group"> <label asp-for="ContactName"></label> <input asp-for="ContactName" class="form-control" /> <span asp-validation-for="ContactName" class="text-danger"></span> </div>
var user = new ApplicationUser { ContactName=model.ContactName, UserName = model.Email, Email = model.Email };
Once Completed Do The Same For:
Now, we need to add the new data to claim for this create a new class with the code below
public class MyUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole> { public MyUserClaimsPrincipalFactory( UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user) { var identity = await base.GenerateClaimsAsync(user); identity.AddClaim(new Claim("ContactName", user.ContactName ?? "")); return identity; } }
Now we need to register it in DI container in ConfigureServices methods of the Startup class as
public void ConfigureServices(IServiceCollection services) { . . services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); //add the following line of code services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, MyUserClaimsPrincipalFactory>(); . . }
So, this is all about the setup. Now for accessing the data in view it can be done by a single line of code as:
@(User.FindFirst("ContactName").Value)
Ref: korzh.com
I just wanted to take a moment to express my gratitude for the great content you consistently produce. It’s informative, interesting, and always keeps me coming back for more!