我有一个扩展IdentityUser的User类。我试图获取在IdentityUser中声明的属性(例如电子邮件),但是当我调用它们时,值似乎没有设置。如何正确访问IdentityUser属性?它们应该在登录时设置。正确设置了其他属性(名为LGID)。
我如何调用属性
var identity = (ClaimsIdentity)User.Identity;
var user = new ApplicationUser(identity);
//do something with user.Email
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public string LGID { get; } = "";
public ApplicationUser() { }
public ApplicationUser(ClaimsIdentity identity)
{
IEnumerable<Claim> claims = identity.Claims;
foreach (Claim c in claims)
{
if (c.Type == "LGID")
LGID = c.Value;
}
}
}
IdentityUser.cs
namespace Microsoft.AspNetCore.Identity
{
//
// Summary:
// The default implementation of Microsoft.AspNetCore.Identity.IdentityUser`1 which
// uses a string as a primary key.
public class IdentityUser : IdentityUser<string>
{
//
// Summary:
// Initializes a new instance of Microsoft.AspNetCore.Identity.IdentityUser.
//
// Remarks:
// The Id property is initialized to form a new GUID string value.
public IdentityUser();
//
// Summary:
// Initializes a new instance of Microsoft.AspNetCore.Identity.IdentityUser.
//
// Parameters:
// userName:
// The user name.
//
// Remarks:
// The Id property is initialized to form a new GUID string value.
public IdentityUser(string userName);
}
}
登录方法(自动生成)
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:0)
您需要先设置它们xD
登录后(!)在您想要电子邮件地址的操作中调用它。
vertical-align: middle