一、定義擴展類session
/// <summary> /// IAbpSession擴展類 /// </summary> public static class SessionExtensions { /// <summary> /// 當前用戶角色信息 /// </summary> /// <param name="session"></param> /// <returns></returns> public static string GetRolesCode(this IAbpSession session) { try { var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal; var claim = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == "rolesCode"); if (claim == null || string.IsNullOrEmpty(claim.Value)) { return null; } return claim.Value.ToString(); } catch { return null; } } }
二、爲擴展的abpssion填充數據,能夠在全局入口或者過濾器中定義。這裏我使用action過濾器來作。ide
public class MyActionFilterAttribute : ActionFilterAttribute { private LoginMode _loginModel; /// <summary> /// 過濾器 /// </summary> /// <param name="loginModel">登陸類型</param> public MyActionFilterAttribute(LoginMode loginModel) { _loginModel = loginModel; } public override void OnActionExecuting(ActionExecutingContext filterContext) { string authType = ConfigManagerConf.GetValue("AppSetting:AuthType"); if (authType == "debug") { string userId = "0"; string userName = "system"; string allCompany = "true"; string companyId = "1"; string rolecode = "pps_publish"; CreateIdentity(userId, userName, allCompany, companyId, rolecode, filterContext.HttpContext); } base.OnActionExecuting(filterContext); } /// <summary> /// 添加用戶數據到ClaimsIdentity,爲擴展自定義IAbpSession準備數據 /// </summary> /// <param name="userId"></param> /// <param name="userName"></param> /// <param name="allCompany"></param> /// <param name="companyId"></param> private void CreateIdentity(string userId, string userName, string allCompany, string companyId, string rolecodes, HttpContext HttpContext) { var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String)); claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String)); claimsIdentity.AddClaim(new Claim("IsAllCompany", allCompany, ClaimValueTypes.String)); claimsIdentity.AddClaim(new Claim("CompanyId", companyId, ClaimValueTypes.String)); claimsIdentity.AddClaim(new Claim("rolesCode", rolecodes, ClaimValueTypes.String)); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); Thread.CurrentPrincipal = claimsPrincipal; HttpContext.SignInAsync(claimsPrincipal); Thread.Sleep(10); } }
這樣,就能夠直接在應用層經過AbpSession或者在表示層構造函數注入IAbpSession來獲取擴展字段的值了。函數