當前Abp版本1.2,項目類型為MVC5.
以屬性的形式擴展AbpSession,並在"記住我"後,下次自動登錄也能獲取到擴展屬性的值,版權歸"角落的白板報"所有!
step1.添加IAbpSessionExtensions接口:
/// <summary> /// IAbpSession Extensions 登錄時"記住我"保存Cookie,也就是說關閉後再打開不重新登錄的話,取得到值. /// </summary> public interface IAbpSessionExtensions : IAbpSession { string UserName { get; } string EmailAddress { get; } string Name { get; } string FullName { get; } string Surname { get; } }
step2.添加實現類AbpSessionExtensions:
/// <summary> /// IAbpSession Extensions /// </summary> public class AbpSessionExtensions : ClaimsAbpSession, IAbpSessionExtensions { public AbpSessionExtensions(IMultiTenancyConfig multiTenancy) : base(multiTenancy) { } public string EmailAddress => GetKeyValue(ClaimTypes.Email); public string Surname => GetKeyValue(ClaimTypes.Surname); public string Name => GetKeyValue(ClaimTypes.Name); public string UserName => GetKeyValue(EnglishConsts.ClaimTypes.UserName); public string FullName => GetKeyValue(EnglishConsts.ClaimTypes.FullName); private string GetKeyValue(string key) { var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal; if (claimsPrincipal == null) { return null; } var claim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == key); if (string.IsNullOrEmpty(claim?.Value)) { return null; } return claim.Value; } }
step3.在Mvc控制器基類(項目名稱ControllerBase)裡添加AbpSession屬性:
//IAbpSession Extensions public new IAbpSessionExtensions AbpSession { get; set; }
step4.在Account控制器的SignInAsync方法裡成功登錄後(AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, identity),添加需要擴展的屬性:
//IAbpSession Extensions identity.AddClaim(new Claim(ClaimTypes.Email, user.EmailAddress)); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); identity.AddClaim(new Claim(ClaimTypes.Surname, user.Surname));
//這個常量自己去定義 identity.AddClaim(new Claim(EnglishConsts.ClaimTypes.UserName, user.UserName)); identity.AddClaim(new Claim(EnglishConsts.ClaimTypes.FullName, user.FullName));
step5.這裡我定義了兩個自定義常量,加在了項目名稱Consts常量定義文件裡:
public class EnglishConsts { public const string LocalizationSourceName = "English"; public class ClaimTypes { public const string UserName = "UserName"; public const string FullName = "FullName"; } }
這樣就完成了,登錄或下次自動登錄之後,在代碼裡的智能提示裡就可以看到擴展的屬性:
而且值也保存在了裡面: