繁体   English   中英

如何在实体框架中显示注册用户的姓名而不是电子邮件

[英]How to show the name of the registered user in Entity Framework instead of email

实际上,我对 .NET Core Identity and Entity Framework 非常陌生。 我正在编写一个 .NET Core razor pages 项目。 我在我的项目中使用个人身份功能,所以注册我可以看到_Loginpartial.cshtml页面中显示的“嗨和注册用户的邮件 ID”。

它正在使用@User.Identity.Name!

代码行是:

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

但我想显示全名而不是名称(Emailid)。 我创建了一个名为ApplicationUser的域类,其中包含我的其他用户详细信息,并且它扩展了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; }
}

我正在使用导航。

所以在我的导航栏中,我想要注册后的全名,即FullName ,所以如何在登录部分页面中显示它。 请帮忙..

所以为了更清楚,我添加了具有这 4 个属性的域类..然后我将它注入 ApplicationDbcontext 类..

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

从包管理器控制台之后,我添加了迁移..更新了数据库....然后我确实为应用程序用户类实现了。 我的 Register.cshtml.cs 类:--

namespace New11.Areas.Identity.Pages.Account

{ [AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager _signInManager; 私有只读 UserManager _userManager; 私有只读 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();
    }
}

我添加了 AddIdentity 代替 AddDefaultIdentity 部分是: -

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

这是我现在的文件夹结构:在此处输入图像描述

所以在我的导航栏中,我想要注册后的全名,即 FullName,所以如何在登录部分页面中显示它。

您还可以使用 AspNetUsers 的用户名来设置您的全名。

@inject SignInManager<ApplicationUser> SignInManager//ApplicationUser or IdentityUser depends on how you registered in ConfigureServices
@inject UserManager<ApplicationUser> UserManager
<ul class="navbar-nav">
@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item">
        <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
    </li>

结果:

在此处输入图像描述

很高兴看到您的更新,您无法访问 html 页面中的FullName属性的原因是因为您使用不同的类来显示它。 在返回您的帖子时,您应该返回一个ApplicationUser类型的填充对象,这将是您的情况下的用户。

return Redirect(returnUrl, user);

为了确保您的视图解释您的模型,您将其定义为页面模型。 或者,如果您已经有一个类作为页面的模型,则将其添加到该模型中。

如果您没有模型,请将其添加到页面顶部。

@model ApplicationUser

您现在可以使用@Model.FullNameApplicationUser类访问数据 大写在这里非常重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM