У меня есть класс User, который расширяет IdentityUser. Я пытаюсь получить свойства, объявленные в 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);
}