[英]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.FullName
從ApplicationUser
類訪問數據 大寫在這里非常重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.