如何向User.Identity添加另一个Propertys来自身份2.2.1中的表AspNetUsers
我首先在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 GenerateUserIdentityAsync(UserManager 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; } }
好的,现在我想调用Profile Picture,例如这段代码:User.Identity.ProfilePicture;
解决方案是:
您需要创建自己的类来实现IIdentity和IPrincipal。 然后在OnPostAuthenticate的global.asax中分配它们。
但我不知道该怎么做!! 如何创建我自己的实现IIdentity和IPrincipal的类。 然后在OnPostAuthenticate的global.asax中分配它们。 谢谢 。
你有2个选项(至少)。 首先,在用户登录时将您的附加属性设置为声明,然后在每次需要时从声明中读取属性。 其次,每次需要属性时,都要从存储(DB)中读取它。 虽然我推荐基于声明的方法,但速度更快,我会通过使用扩展方法向您展示。
第一种方法:
将您自己的声明放在GenerateUserIdentityAsync
方法中,如下所示:
public class ApplicationUser : IdentityUser { // some code here public async Task GenerateUserIdentityAsync(UserManager 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(); 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;