标签:app sleep class returns catch 入口 net .net identity
1、定义扩展类
/// <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; } } }
2、为扩展的abpssion填充数据,可以在全局入口或者过滤器中定义。这里我使用action过滤器来做。
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来获取扩展字段的值了。
标签:app sleep class returns catch 入口 net .net identity
原文地址:https://www.cnblogs.com/KQNLL/p/10327467.html