[英]ASP.NET Identity - Extend available fields of User.Identity
I'm struggling to show FirstName in my shared view.我正在努力在我的共享视图中显示名字。 Please see my the code below and let me know where I got it wrong.
请查看我下面的代码,让我知道我哪里出错了。
The AppUser class in IdentityModels has been extended to include FirstName. IdentityModels 中的 AppUser 类已扩展为包括 FirstName。 In debug mode,
var claim
is null and I couldn't figure out why?在调试模式下,
var claim
为空,我不知道为什么?
IdentityExtensions.cs身份扩展.cs
public static class IdentityExtensions
{
public static string FirstName(this IPrincipal usr)
{
var claim = ((ClaimsIdentity)usr.Identity).FindFirst("FirstName");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
AppUser.cs应用用户.cs
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<AppUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FirstName", FirstName));
userIdentity.AddClaim(new Claim("Surname", Surname));
return userIdentity;
}
}
In the view, I could see the method FirstName(), however it returns empty string _Layout.cshtml在视图中,我可以看到方法 FirstName(),但是它返回空字符串_Layout.cshtml
@HttpContext.Current.User.FirstName()
AccountController.cs账户控制器.cs
public class AccountController : Controller
{
public async Task<ActionResult> SignIn(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
}
CreateUserIdentityAsync
was missing.缺少
CreateUserIdentityAsync
。 By adding it, I managed to get the FirstName and other properties I added.通过添加它,我设法获得了我添加的 FirstName 和其他属性。
public class ApplicationSignInManager : SignInManager<AppUser, string>
{
public override Task<ClaimsIdentity> CreateUserIdentityAsync(AppUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
}
Thanks谢谢
simply just edit your Register Action to this只需将您的注册操作编辑为此
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = "MyFirstName" };
you have to set the value of the FirstName in your Register Action您必须在注册操作中设置 FirstName 的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.