ASP.NET标识 - 扩展User.Identity的可用字段

时间:2018-02-16 12:11:02

标签: asp.net-mvc asp.net-identity claims-based-identity

我在共享视图中努力展示FirstName。请参阅下面的代码,让我知道我哪里弄错了。

IdentityModels中的AppUser类已扩展为包含FirstName。 在调试模式下,var claim为空,我无法找出原因?

IdentityExtensions.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

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;
        }

    }

在视图中,我可以看到方法FirstName(),但它返回空字符串 的 _Layout.cshtml

@HttpContext.Current.User.FirstName()

AccountController.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);
            }
        }
}

2 个答案:

答案 0 :(得分:0)

CreateUserIdentityAsync失踪了。通过添加它,我设法获得了我添加的FirstName和其他属性。

public class ApplicationSignInManager : SignInManager<AppUser, string>
        {
            public override Task<ClaimsIdentity> CreateUserIdentityAsync(AppUser user)
            {
                return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
            }

        }

由于

答案 1 :(得分:-1)

只需将您的注册操作编辑为此

即可
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = "MyFirstName" };

您必须在注册操作

中设置FirstName的值