扩展ClaimsAbpSession

时间:2017-08-21 16:49:00

标签: aspnetboilerplate

我需要扩展ClaimsAbpSession并创建要在角应用和服务器之间的请求中发送的新属性。

实际上,我已经使用声明存储了这些新属性。但是,当用户刷新页面时,声明中的值将丢失。

1 个答案:

答案 0 :(得分:1)

<强> MyAppSession.cs

// Define your own session and add your custom field to it.
// Then, you can inject MyAppSession and use its new property in your project.
public class MyAppSession : ClaimsAbpSession, ITransientDependency
{
    public MyAppSession(
        IPrincipalAccessor principalAccessor,
        IMultiTenancyConfig multiTenancy,
        ITenantResolver tenantResolver,
        IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) : 
        base(principalAccessor, multiTenancy, tenantResolver, sessionOverrideScopeProvider)
    {   
    }

    public string UserEmail
    {
        get
        {
            var userEmailClaim = PrincipalAccessor.Principal?.Claims.FirstOrDefault(c => c.Type == "Application_UserEmail");
            if (string.IsNullOrEmpty(userEmailClaim?.Value))
            {
                return null;
            }

            return userEmailClaim.Value;
        }
    }
}

<强> UserClaimsPrincipalFactory.cs

// Override CreateAsync method to add your custom claim
public override async Task<ClaimsPrincipal> CreateAsync(User user)
{
    var claim = await base.CreateAsync(user);
    claim.Identities.First().AddClaim(new Claim("Application_UserEmail", user.EmailAddress));
    return claim;
}