如何在Identity 2.2.1中从表AspNetUsers中添加其他属性到User.Identity?

7

我为Asp.net Identity 2.2.1 (AspNetUsers表) Code First添加了一些新属性。

 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;

解决方案是:

您需要创建自己的类来实现IIdentity和IPrincipal。然后在global.asax的OnPostAuthenticate中分配它们。

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

1个回答

11

你有至少两种选择。首先,在用户登录时将您的附加属性设置为声明,然后每次需要时从声明中读取该属性。其次,每次需要该属性时,从存储(数据库)中读取它。虽然我建议使用基于声明的方法,因为这种方法更快,但我将通过使用扩展方法展示两种方法。

第一种方法:

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;

2
有没有办法从属性中获取它,而不是从方法中获取? - luisluix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接