Asp.net Boilerplate之AbpSession扩展

当前Abp版本1.4.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
{ /// 如果是之前的版本,此处的构造函数会有所不同,只要把这个构造函数删除,再根据Vs的提示生成默认实现就可以.

      public AbpSessionExtensions(IPrincipalAccessor principalAccessor,
        IMultiTenancyConfig multiTenancy, ITenantResolver tenantResolver,
        IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider)
          : base(principalAccessor, multiTenancy, tenantResolver, sessionOverrideScopeProvider)
      {
      }

     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";
}
}

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

Asp.net Boilerplate之AbpSession扩展

而且值也保存在了里面:

Asp.net Boilerplate之AbpSession扩展

上一篇:lambda 表达式 比较时间大小


下一篇:[BTS] WCF-SAP adapter