如何在身份 2.2.1 中从 table AspNetUsers 添加另一个属性到 User.Identity

How to Add another Propertys to User.Identity From table AspNetUsers in identity 2.2.1

我先添加一些新的 属性 到 asp.net identity 2.2.1 (AspNetUsers table) 代码

 public class ApplicationUser : IdentityUser
    {
        public string AccessToken { get; set; }

        public string FullName { get; set; }

        public string ProfilePicture { get; set; }


        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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

            return userIdentity;
        }
    }

好的,现在我要调用个人资料图片,例如以下代码: User.Identity.ProfilePicture;

解决方案是:

You need to create your own classes that implement IIdentity and IPrincipal. Then assign them in your global.asax in OnPostAuthenticate.

但我不知道该怎么做!!如何创建我自己的 类 来实现 IIdentity 和 IPrincipal。然后在 OnPostAuthenticate 的 global.asax 中分配它们。 谢谢 。

您有 2 个选项(至少)。首先,在用户登录时将额外的 属性 设置为声明,然后在每次需要时从声明中读取 属性。其次,每次您需要 属性 从存储(DB)中读取它。虽然我推荐更快的基于声明的方法,但我将通过使用扩展方法向您展示这两种方法。

第一种方法:

像这样在 GenerateUserIdentityAsync 方法中加入您自己的声明:

public class ApplicationUser : IdentityUser
{
    // some code here

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("ProfilePicture", this.ProfilePicture));
        return userIdentity;
    }
}

然后编写一个扩展方法来轻松读取这样的声明:

public static class IdentityHelper
{
    public static string GetProfilePicture(this IIdentity identity)
    {
        var claimIdent = identity as ClaimsIdentity;
        return claimIdent != null
            && claimIdent.HasClaim(c => c.Type == "ProfilePicture")
            ? claimIdent.FindFirst("ProfilePicture").Value
            : string.Empty;
    }
}

现在您可以像这样轻松地使用您的扩展方法:

var pic = User.Identity.GetProfilePicture();

第二种方法:

如果您更喜欢新鲜数据而不是索赔中的兑现数据,您可以编写另一种扩展方法来从用户管理器中获取 属性:

public static class IdentityHelper
{
    public static string GetFreshProfilePicture(this IIdentity identity)
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        return userManager.FindById(identity.GetUserId()).ProfilePicture;
    }
}

现在只需这样使用:

var pic = User.Identity.GetFreshProfilePicture();

另外不要忘记添加相关的命名空间:

using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;