Home > Software engineering >  How to show the name of the registered user in Entity Framework instead of email
How to show the name of the registered user in Entity Framework instead of email

Time:05-20

Actually I am very new to .NET Core Identity and Entity Framework. I am writing a .NET Core razor pages project. I am using individual identity feature in my project so aster registering I am am able to see the 'Hi and the mail id of registered user' that is shown in the _Loginpartial.cshtml page.

It is using @User.Identity.Name!

The code line is:

<a  asp-area="Identity" asp-page="/Account/Manage/Index" 
   title="Manage">Hello @User.Identity.Name!</a>

But I want to show the full name instead of Name (Emailid). I created a domain class named ApplicationUser which has my other user details, and it extends IdentityUser.

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
}

I am using navigation.

So in my navbar I want the full name after register which is FullName so how to show that in login partial page. please help..

so for more clarity i added that domain class with that 4 properties....then i injected it in ApplicationDbcontext class..

 public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    public DbSet<ApplicationUser> ApplicationUser { get; set; }
}

after that from package manager console i added that migration..updated the database ....then i did made implementation for Application user class. My Register.cshtml.cs class:--

namespace New11.Areas.Identity.Pages.Account

{ [AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager _signInManager; private readonly UserManager _userManager; private readonly ILogger _logger;

    ////comented the Iemailsender because its causing error.
    // private readonly IEmailSender _emailSender;

    //// added by me for dependency injection;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly ApplicationDbContext _db;

    
    public RegisterModel(
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager,
        ILogger<RegisterModel> logger,
        // IEmailSender emailSender,
        ////added by me for constructor for the upper used dependency injection;
        RoleManager<IdentityRole> roleManager,
        ApplicationDbContext db)
        
        
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        // _emailSender = emailSender;
        ////added by me for upper used constructor;
        _roleManager = roleManager;
        _db = db;

    }

    [BindProperty]
    public InputModel Input { get; set; }

    public string ReturnUrl { get; set; }

    public IList<AuthenticationScheme> ExternalLogins { get; set; }

    public class InputModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        //added by me
        [Required]
        public string FullName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }

        [Required]
        public string PhoneNumber { get; set; }
    }

    public async Task OnGetAsync(string returnUrl = null)
    {
        ReturnUrl = returnUrl;
        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
    }

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        if (ModelState.IsValid)
        {
            //// var user = new Identityuser { UserName = Input.Email, Email = Input.Email };...I edited it because in Applicationuser class i am putting the name,address,city,postal code.
            var user = new ApplicationUser
            { 
                UserName = Input.Email, 
                Email = Input.Email ,
                FullName = Input.FullName,
                Address = Input.Address,
                City = Input.City,
                PostalCode = Input.PostalCode,
                PhoneNumber = Input.PhoneNumber

            };
            ////after dependency injection we come to after post handler.and in below line they r creating the user.
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {
                ////added by me if this is successful we want chk if role exits in the detabase.
                ////if admin user doesnot exits we want to creat it.
                ////StaticDetails class SD created by me.
                if (!await _roleManager.RoleExistsAsync(StaticDetails.AdminEndUser))
                {
                    await _roleManager.CreateAsync(new IdentityRole(StaticDetails.AdminEndUser));
                }

                if (!await _roleManager.RoleExistsAsync(StaticDetails.HrEndUser))
                {
                    await _roleManager.CreateAsync(new IdentityRole(StaticDetails.HrEndUser));
                }

                if (!await _roleManager.RoleExistsAsync(StaticDetails.ItEndUser))
                {
                    await _roleManager.CreateAsync(new IdentityRole(StaticDetails.ItEndUser));
                }
                if (!await _roleManager.RoleExistsAsync(StaticDetails.EmployeeEndUser))
                {
                    await _roleManager.CreateAsync(new IdentityRole(StaticDetails.EmployeeEndUser));
                }

                ////roles are created now have to assign it to a user.
                ////adminuser for now.means when i will creat it will by default take adminuser.
                await _userManager.AddToRoleAsync(user, StaticDetails.EmployeeEndUser);


                _logger.LogInformation("User created a new account with password.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                    protocol: Request.Scheme);

               // await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                 //   $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                if (_userManager.Options.SignIn.RequireConfirmedAccount)
                {
                    return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                }
                else
                {
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        // If we got this far, something failed, redisplay form
        return Page();
    }
}

and i added AddIdentity in place of AddDefaultIdentity the part is:-

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddRazorPages();
    }

this is my folder structure as if now: enter image description here

  • Related