查看: 2972|回复: 0

[.NET源码] Asp.net Boilerplate之AbpSession扩展

发表于 2017-1-11 19:15:07
太阳http代理AD

当前Abp版本1.2,项目类型为MVC5.

以属性的形式扩展AbpSession,并在"记住我"后,下次自动登录也能获取到扩展属性的值,版权归"角落的白板报"所有!

step1.添加IAbpSessionExtensions接口:

  1. /// <summary>
  2. /// IAbpSession Extensions 登录时"记住我"保存Cookie,也就是说关闭后再打开不重新登录的话,取得到值.
  3. /// </summary>
  4. public interface IAbpSessionExtensions : IAbpSession
  5. {
  6. string UserName { get; }
  7. string EmailAddress { get; }
  8. string Name { get; }
  9. string FullName { get; }
  10. string Surname { get; }
  11. }
复制代码

step2.添加实现类AbpSessionExtensions:

  1. /// <summary>
  2. /// IAbpSession Extensions
  3. /// </summary>
  4. public class AbpSessionExtensions : ClaimsAbpSession, IAbpSessionExtensions
  5. {
  6. public AbpSessionExtensions(IMultiTenancyConfig multiTenancy) : base(multiTenancy)
  7. {
  8. }
  9. public string EmailAddress => GetKeyValue(ClaimTypes.Email);
  10. public string Surname => GetKeyValue(ClaimTypes.Surname);
  11. public string Name => GetKeyValue(ClaimTypes.Name);
  12. public string UserName => GetKeyValue(EnglishConsts.ClaimTypes.UserName);
  13. public string FullName => GetKeyValue(EnglishConsts.ClaimTypes.FullName);
  14. private string GetKeyValue(string key)
  15. {
  16. var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
  17. if (claimsPrincipal == null)
  18. {
  19. return null;
  20. }
  21. var claim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == key);
  22. if (string.IsNullOrEmpty(claim?.Value))
  23. {
  24. return null;
  25. }
  26. return claim.Value;
  27. }
  28. }
复制代码

step3.在Mvc控制器基类(项目名称ControllerBase)里添加AbpSession属性:

  1. //IAbpSession Extensions
  2. public new IAbpSessionExtensions AbpSession { get; set; }
复制代码

step4.在Account控制器的SignInAsync方法里成功登录后(AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, identity),添加需要扩展的属性:

  1. //IAbpSession Extensions
  2. identity.AddClaim(new Claim(ClaimTypes.Email, user.EmailAddress));
  3. identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
  4. identity.AddClaim(new Claim(ClaimTypes.Surname, user.Surname));<br />       //这个常量自己去定义
  5. identity.AddClaim(new Claim(EnglishConsts.ClaimTypes.UserName, user.UserName));
  6. identity.AddClaim(new Claim(EnglishConsts.ClaimTypes.FullName, user.FullName));
复制代码

step5.这里我定义了两个自定义常量,加在了项目名称Consts常量定义文件里:

  1. public class EnglishConsts
  2. {
  3. public const string LocalizationSourceName = "English";
  4. public class ClaimTypes
  5. {
  6. public const string UserName = "UserName";
  7. public const string FullName = "FullName";
  8. }
  9. }
复制代码

这样就完成了,登录或下次自动登录之后,在代码里的智能提示里就可以看到扩展的属性:

而且值也保存在了里面:



太阳http代理AD
回复

使用道具 举报