public string GetOpenId() { //从Header中获取Token var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", ""); bool isKey = _redisCacheManager.Get(tokenHeader); string openId = string.Empty; if (isKey) { //根据Token中的信息获取到OpenId openId = _redisCacheManager.GetValue(tokenHeader).ToString().Split(";")[0].Trim('"'); } return(openId); }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; if (method.ReturnType.Equals(typeof(void)) || method.ReturnType.Equals(typeof(Task))) { invocation.Proceed(); return; } var methodCacheAttribute = method.GetCustomAttributes(true).FirstOrDefault(a => a.GetType().Equals(typeof(MethodCacheAttribute))) as MethodCacheAttribute; if (methodCacheAttribute != null) { var cacheKey = CustomCacheKey(invocation); var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { Type returnType; if (typeof(Task).IsAssignableFrom(method.ReturnType)) { returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault(); } else { returnType = method.ReturnType; } dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnType); invocation.ReturnValue = (typeof(Task).IsAssignableFrom(returnType)) ? Task.FromResult(result) : result; return; } invocation.Proceed(); if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromSeconds(methodCacheAttribute.AbsoluteExpiration)); } } else { invocation.Proceed(); } }
public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var cachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; //只有那些指定的才可以被缓存,需要验证 if (cachingAttribute != null) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //根据key获取相应的缓存值 var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { Type returnType; if (typeof(Task).IsAssignableFrom(method.ReturnType)) { returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault(); } else { returnType = method.ReturnType; } dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnType); invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(result) : result; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromMinutes(cachingAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接执行被拦截方法 } }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; if (method.ReturnType == typeof(void) || method.ReturnType == typeof(Task)) { invocation.Proceed(); return; } // 对当前方法的特性判断 if (method.GetCustomAttribute(typeof(CacheAttribute)) is CacheAttribute cacheAttribute) { // //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); var cacheValue = _redisCacheManager.GetValue(cacheKey); if (cacheValue != null) { var returnType = typeof(Task).IsAssignableFrom(method.ReturnType) ? method.ReturnType.GenericTypeArguments.FirstOrDefault() : method.ReturnType; var result = Json.FromJsonDynamic(returnType, cacheValue); invocation.ReturnValue = typeof(Task).IsAssignableFrom(method.ReturnType) ? Task.FromResult(result) : result; } else { invocation.Proceed(); // 存储缓存 if (!cacheKey.IsNullOrEmpty()) { object response; var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } response ??= string.Empty; // if (response == null) response = string.Empty; _redisCacheManager.Set(cacheKey, response, TimeSpan.FromMinutes(cacheAttribute.AbsoluteExpiration)); } } } else { invocation.Proceed(); } }
public IActionResult GenerateJWTToken() { try { bool ismyOpenId = _redisCacheManager.Get("myOpenId"); bool ismySessionKey = _redisCacheManager.Get("mySessionKey"); string OpenId = string.Empty; string SessionKey = string.Empty; if (ismyOpenId && ismySessionKey) { OpenId = _redisCacheManager.GetValue("myOpenId").ToString().Trim('"'); SessionKey = _redisCacheManager.GetValue("mySessionKey").ToString().Trim('"'); } if (OpenId == "") { throw new Exception("OpenId为空,获取token失败!"); } string userId = OpenId + ";" + SessionKey; string jwtStr = string.Empty; bool suc = false; TokenModel tokenModel = new TokenModel { OpenId = OpenId }; jwtStr = JwtHelper.IssueJwt(tokenModel);//登录,获取到一定规则的 Token 令牌 suc = true; _redisCacheManager.Set(jwtStr, userId, TimeSpan.FromHours(2)); return(Ok(new { success = suc, token = jwtStr })); } catch (Exception err) { _logger.Error(typeof(AuthController), "获取token失败!", new Exception(err.Message)); return(FailedMsg(err.Message)); } }
public async Task Invoke( HttpContext context, LoginUser user ) { if (context.Request.Path.StartsWithSegments("/swagger") || context.Request.Path.StartsWithSegments("/health") || context.Request.Path.StartsWithSegments("/ping") || context.Request.Path.StartsWithSegments("/api/metrics")) { await this._next(context); return; } if (context.User?.Identity.IsAuthenticated == true) { var employeeId = context.User.Identity.Name; var cacheValue = _cache.GetValue(employeeId); if (cacheValue != null) { user = JsonConvert.DeserializeObject <LoginUser>(cacheValue); } else { user.EmployeeId = employeeId; user.IsLogin = true; var data = _myDbContext.AspNetUsers.Where(s => s.UserName == employeeId).FirstOrDefault(); user.Email = data.Email; _cache.Set(employeeId, user, TimeSpan.FromMinutes(10)); } } // 取得 Session ID var sessionId = context.User?.FindFirst(c => c.Type == "session_id")?.Value; if (!string.IsNullOrEmpty(context.Request.ContentType) && context.Request.ContentType.Contains("multipart/form-data")) { await this._next(context); } else { await this._next(context); } }
/// <summary> /// 查询用户是否存在 /// </summary> /// <returns></returns> public async Task <Wx_UserInfo> GetUserInfoExists(string tokenHeader) { string OpenId = string.Empty; bool isKey = _redisCacheManager.Get(tokenHeader); if (isKey) { OpenId = _redisCacheManager.GetValue(tokenHeader).ToString().Split(";")[0].Trim('"'); } return(await Task.Run(() => { var result = db.Queryable <Wx_UserInfo>().Where(it => it.OpenId == OpenId).FirstAsync(); return result; })); }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var qCacheAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCacheAttribute != null) { //获取自定义缓存键 var cacheKey = CustomCacheKey(invocation); //注意是 string 类型,方法GetValue var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response; if (typeof(Task).IsAssignableFrom(type)) { if (resultTypes.Any()) { var resultType = resultTypes.FirstOrDefault(); dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //dynamic temp = System.Convert.ChangeType(cacheValue, resultType); // System.Convert.ChangeType(Task.FromResult(temp), type); response = Task.FromResult(temp); } else { response = Task.Yield(); } } else { response = Convert.ChangeType(_cache.GetValue(cacheKey), type); } invocation.ReturnValue = response; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCacheAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接执行被拦截方法 } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 //代码已经合并 ,学习pr流程 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; if (method.ReturnType == typeof(void) || method.ReturnType == typeof(Task)) { invocation.Proceed(); return; } //对当前方法的特性验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) is CachingAttribute qCachingAttribute) { //获取自定义缓存键 var cacheKey = qCachingAttribute.CustomKeyValue ?? CustomCacheKey(invocation); var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { if (qCachingAttribute.IsDelete) { //删除Redis里面的数据 _cache.Remove(cacheKey); } else { //将当前获取到的缓存值,赋值给当前执行方法 Type returnType; if (typeof(Task).IsAssignableFrom(method.ReturnType)) { returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault(); } else { returnType = method.ReturnType; } dynamic _result = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnType); invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(_result) : _result; return; } } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey) && qCachingAttribute.IsDelete == false) { object response; var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接执行被拦截方法 } }
public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; //拦截 if (qCachingAttribute != null) { //获取自定义缓存键,和Memory内存缓存一样 var cacheKey = CustomCacheKey(invocation); //获取值(string类型)核心一 string cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { //获取返回类型 var type = invocation.Method.ReturnType; if (type.FullName == "System.Void") { return; //如果是同步并且是voi类型,返回 } var resultTypes = type.GenericTypeArguments; //拿到泛型参数 object response; if (type != null && typeof(Task).IsAssignableFrom(type)) //异步 { //返回异步的对象Task<T>核心二 if (resultTypes.Count() > 0)//泛型的参数存在 { var resultType = resultTypes.FirstOrDefault(); dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //把自定义key转为泛型参数同一个类型 response = Task.FromResult(temp); //然后放入response } else { //Task无返回方法,指定时间不允许重新运行 response = Task.Yield(); } } else//如果是同步的,把获取的值转为返回值类型即可 { //核心4,要进行ChangeType response = System.Convert.ChangeType(_cache.Get <object>(cacheKey), type); } invocation.ReturnValue = response; return; } invocation.Proceed();//执行方法 //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { //异步拿到Task里面的result的方法 var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; //如果返回值是空 } //核心5:将获取到指定的response 和特性的缓存时间,进行set操作 _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } else { //直接执行被拦截的方法 invocation.Proceed(); } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //获取自定义缓存键,这个和Memory内存缓存是一样的,不细说 var cacheKey = CustomCacheKey(invocation); //核心1:注意这里和之前不同,是获取的string值,之前是object var cacheValue = Cache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response = null; if (typeof(Task).IsAssignableFrom(type)) { //返回Task<T> if (resultTypes.Any()) { var resultType = resultTypes.FirstOrDefault(); // 核心1,直接获取 dynamic 类型 dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); //dynamic temp = System.Convert.ChangeType(cacheValue, resultType); // System.Convert.ChangeType(Task.FromResult(temp), type); response = Task.FromResult(temp); } else { //Task 无返回方法 指定时间内不允许重新运行 response = Task.Yield(); } } else { //将缓存返回给调用者 if (type == typeof(SingleApiResponse)) { response = Cache.Get <SingleApiResponse>(cacheKey); } else if (type == typeof(ListApiResponse)) { response = Cache.Get <ListApiResponse>(cacheKey); } } invocation.ReturnValue = response; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; //Type type = invocation.ReturnValue?.GetType(); var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } // 核心5:将获取到指定的response 和特性的缓存时间,进行set操作 Cache.Set(cacheKey, response, TimeSpan.FromMilliseconds(qCachingAttribute.AbsoluteExpiration)); } } else { //直接执行被拦截方法 invocation.Proceed(); } }
//Intercept方法是攔截的關鍵所在,也是IInterceptor接口中的唯一定義 //代碼已經合並 ,學習pr流程 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; if (method.ReturnType == typeof(void) || method.ReturnType == typeof(Task)) { invocation.Proceed(); return; } //對當前方法的特性驗證 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //獲取自定義緩存鍵 var cacheKey = CustomCacheKey(invocation); //注意是 string 類型,方法GetValue var cacheValue = _cache.GetValue(cacheKey); if (cacheValue != null) { //將當前獲取到的緩存值,賦值給當前執行方法 Type returnType; if (typeof(Task).IsAssignableFrom(method.ReturnType)) { returnType = method.ReturnType.GenericTypeArguments.FirstOrDefault(); } else { returnType = method.ReturnType; } dynamic _result = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnType); invocation.ReturnValue = (typeof(Task).IsAssignableFrom(method.ReturnType)) ? Task.FromResult(_result) : _result; return; } //去執行當前的方法 invocation.Proceed(); //存入緩存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; //Type type = invocation.ReturnValue?.GetType(); var type = invocation.Method.ReturnType; if (typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } _cache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } else { invocation.Proceed();//直接執行被攔截方法 } }
//Intercept方法是拦截的关键所在,也是IInterceptor接口中的唯一定义 public override void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法特性验证 var qCachingAttribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(CachingAttribute)) as CachingAttribute; if (qCachingAttribute != null) { //获取自定义缓存键,这个和Memory内存缓存是一样的 var cacheKey = CustomCacheKey(invocation); //核心1:注意这里和之前不同,是获取的string值,之前是object var cacheValue = _redisCache.GetValue(cacheKey); if (cacheValue != null) { //将当前获取到的值,赋给当前执行的方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") { return; } object response; if (type != null && typeof(Task).IsAssignableFrom(type)) { //核心2:异步返回Task<T> if (resultTypes.Count() > 0) { var resultType = resultTypes.FirstOrDefault(); //核心3:直接序列化dynamic类型, dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, resultType); response = Task.FromResult(temp); } else { response = Task.Yield(); } } else { //核心4:要进行changeType response = System.Convert.ChangeType(_redisCache.Get <object>(cacheKey), type); } invocation.ReturnValue = response; return; } //去执行当前的方法。 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else { response = invocation.ReturnValue; } if (response == null) { response = string.Empty; } // 核心5:将获取到指定的response 和特性的缓存时间,进行set操作 _redisCache.Set(cacheKey, response, TimeSpan.FromMinutes(qCachingAttribute.AbsoluteExpiration)); } } invocation.Proceed(); }
/// <summary> /// 添加成员 /// </summary> /// <param name="dto"></param> /// <returns></returns> public async Task <bool> PostTeamMemberAsync(AddTeamMemberDto dto, string openId) { var isAny = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == openId).Any(); var result = 0; return(await Task.Run(() => { if (isAny == false) { Wx_UserInfo userInfo = iMapper.Map <Wx_UserInfo>(dto); userInfo.ID = IdHelper.CreateGuid(); userInfo.OpenId = openId; db.Insertable(userInfo).ExecuteCommand(); } //获取邀请人的UserId bool isInviterToken = _redisCacheManager.Get(dto.InviterToken); string InviterUserId = string.Empty; if (isInviterToken) { //根据邀请人Token获取到邀请人OpenId var InviterOenId = _redisCacheManager.GetValue(dto.InviterToken).ToString().Split(";")[0].Trim('"'); InviterUserId = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == InviterOenId).First()?.ID; } var UserInfo = db.Queryable <Wx_UserInfo>().Where(a => a.OpenId == openId).Select(a => new { UserId = a.ID, MobilePhone = a.MobilePhone }).First(); //找到加入人UserId、MobilePhone var roleId = db.Queryable <Role>().Where(a => a.TeamId == dto.TeamId && a.Name == AppConsts.RoleName.Ordinary).First()?.ID; var isMember = db.Queryable <TeamMember>().Where(a => a.TeamId == dto.TeamId && a.IsDeleted == false && a.JoinedUserId == UserInfo.UserId).Any(); if (isMember) { throw new Exception("成员已经加了团队,不能再次加入!"); } else { TeamMember teamMember = iMapper.Map <TeamMember>(dto); teamMember.ID = IdHelper.CreateGuid(); teamMember.TeamNickName = dto.NickName; teamMember.IsDeleted = false; teamMember.InviterUserId = InviterUserId; teamMember.JoinedUserId = UserInfo.UserId; teamMember.RoleId = roleId; result = db.Insertable(teamMember).ExecuteCommand(); if (result > 0 && UserInfo.MobilePhone != null) { db.Updateable <TeamMember>().SetColumns(a => new TeamMember() { MobilePhone = UserInfo.MobilePhone }) .Where(a => a.ID == teamMember.ID).ExecuteCommand(); } } return result > 0; })); }