你能扩展HttpContext.Current.User.Identity属性吗?

有没有办法覆盖HttpContext.Current.User.Identity添加另一个属性(屏幕名称)?

我的应用程序使用Identity ,我将唯一身份保留为电子邮件。 我将用户数据(例如名/姓)存储在单独的"Profile"表中。 有没有办法在HttpContext.Current某处存储这些信息?

它不一定需要在User范围内。 我有一个搜索,并注意到有一个HttpContext.Current.ProfileBase 。 虽然不确定如何使用它 – 而且我真的不希望所有多余的东西都带有它。

如果您使用的是Asp.Net Identity,那么声明很容易实现。

在您的SignInAsync方法中(或者,无论您在何处创建声明标识),请添加GivenNameSurname声明类型:

 private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add the users primary identity details to the set of claims. var your_profile = GetFromYourProfileTable(); identity.AddClaim(new Claim(ClaimTypes.GivenName, your_profile == null ? string.Empty : your_profile.FirstName)); identity.AddClaim(new Claim(ClaimTypes.Surname, your_profile == null ? string.Empty : your_profile.LastName)); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } 

然后,您使用IIdentity的扩展方法将信息从声明标识中提取出来:

 public static ProfileName GetIdentityName(this IIdentity identity) { if (identity == null) return null; var first = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName), var last = (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.Surname) return string.Format("{0} {1}", first, last).Trim(); } internal static string FirstOrNull(this ClaimsIdentity identity, string claimType) { var val = identity.FindFirst(claimType); return val == null ? null : val.Value; } 

然后,在您的应用程序中(在您的控制器或视图中),您可以执行以下操作:

 var name = User.Identity.GetIdentityName(); 

您可以将值放在HttpContext.Current.Items中。 是终身是单一要求的字典。

你可以像这样使用它:

 public static string CurrentScreenName { get { string screenName = (string)HttpContext.Current.Items["CurrentScreenName"]; if (string.NullOrEmpty(screenName)) { screenName = ResolveScreenName(); HttpContext.Current.Items["CurrentScreenName"] = screenName; } return screenName; } } 

对于单个请求,它只会执行一次ResolveScreenName()。

您也可以使用扩展方法从IIdentity访问屏幕名称

 public static class Extensions { public static string GetScreenName(this IIdentity identity) { return CurrentScreenName; } } 

然后像这样使用它:

 string screenName = HttpContext.Current.User.Identity.GetScreenName(); 

我发现了一个实现:

 var profile = db.UserProfile.Where(u => u.UserId == user.Id).FirstOrDefault(); ProfileBase httpProfile = ProfileBase.Create(user.UserName); httpProfile.SetPropertyValue("FullName", profile.FullName); httpProfile.SetPropertyValue("FirstName", profile.FirstName); httpProfile.SetPropertyValue("LastName", profile.LastName); 

然后再来……

 ProfileBase userProfile = ProfileBase.Create(HttpContext.User.Identity.Name); var fullName = userProfile.GetPropertyValue("FullName")); 

绝对! 您需要创建自己的类型,从IPrincipal实现,并自己接管安全性。 您可以在OWIN步骤中对用户进行身份validation,手动设置context.Request.User