如何向User.Identity添加另一个Propertys来自标识2.2.1中的表AspNetUsers

MoH*_*mAd 6 c# asp.net asp.net-identity asp.net-identity-2

我首先向asp.net身份2.2.1(AspNetUsers表)代码添加一些新属性

 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

好的,现在我想调用配置文件图片,例如这段代码:User.Identity.ProfilePicture;

解决方案是:

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

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

Sam*_*ari 10

你有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var pic = User.Identity.GetProfilePicture();
Run Code Online (Sandbox Code Playgroud)

第二种方法:

如果您希望在声明中使用新数据而不是兑现数据,则可以编写另一种扩展方法以从用户管理器获取属性:

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

现在只需使用如下:

var pic = User.Identity.GetFreshProfilePicture();
Run Code Online (Sandbox Code Playgroud)

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

using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法从属性而不是方法中实际获取它? (2认同)