public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { Shop_sys_user user = new Shop_sys_user(); //获取用户 try { if (_redisCacheManager.Get <object>("Redis.sysuser") != null) { user = _redisCacheManager.Get <Shop_sys_user>("Redis.sysuser"); } else { user = await _userServices.GetSysUserByLoginNameAsync(context.UserName); _redisCacheManager.Set("Redis.sysuser", user, TimeSpan.FromHours(10)); } } catch (Exception e) { _redisCacheManager.Set("Redis.sysuser", user, TimeSpan.FromHours(10)); } if (user != null) { if (user.uStatus == 0) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "您已被禁止登陆,请与工作人员联系!"); return; } var _pass = $"{context.Password}{user.passkey}"; var _md5passkey = MD5Helper.MD5Encrypt32(_pass); if (_md5passkey.Equals(user.passValue)) { context.Result = new GrantValidationResult( subject: context.UserName, authenticationMethod: "custom", claims: new Claim[] { new Claim("uid", user.uid + ""), new Claim(JwtClaimTypes.Name, user.loginName), new Claim(JwtClaimTypes.GivenName, user.realName), new Claim(JwtClaimTypes.FamilyName, user.nickName), new Claim(JwtClaimTypes.Email, string.IsNullOrWhiteSpace(user.Email)?"":user.Email), new Claim(JwtClaimTypes.Role, "user") }); return; } else { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "密码不正确!"); return; } } else { //验证失败 context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "不存在该用户名!"); return; } }
public async Task <PageModel <CustomInfo> > Get(int page = 1, string key = "") { if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) { key = ""; } PageModel <CustomInfo> customInfos = new PageModel <CustomInfo>(); try { if (_redisCacheManager.Get <object>("Redis.CustomInfo") != null) { customInfos = _redisCacheManager.Get <PageModel <CustomInfo> >("Redis.CustomInfo"); } else { customInfos = await customInfoServices.QueryPage(a => a.IsDelete != true && (a.Name != "" && a.Name.Contains(key)), page); _redisCacheManager.Set("Redis.CustomInfo", customInfos, TimeSpan.FromHours(2)); } }catch (Exception ex) { } return(customInfos); }
/// <summary> /// 创建组对象 /// </summary> /// <returns></returns> public async override Task OnConnectedAsync() { await Console.Out.WriteLineAsync("SignalR链接初始"); if (Context.User.Claims.Any()) { await Console.Out.WriteLineAsync("SignalR链接成功"); var Id = Context.User.Claims.FirstOrDefault(x => x.Type == "Id").Value.ToGuid(); var name = Context.User.Claims.FirstOrDefault(x => x.Type == "userName").Value; var model = new SignalRModel { UserId = Id, SignalRConnectionId = Context.ConnectionId }; await _redisCacheManager.Set(Id.ToString(), model);//将用户关联的ConnectionID放到缓存中 await Console.Out.WriteLineAsync($"SignalR链接Id放入缓存成功;用户{name}"); } else { await Console.Out.WriteLineAsync("Context.User.Claims未获取到用户信息!"); } await base.OnConnectedAsync(); }
/// <summary> /// 菜单表任何操作将缓存重置 /// </summary> public async void RestMenuCache() { _redisCacheManager.Remove("Menu"); var menus = await GetMenuList(); _redisCacheManager.Set("Menu", menus); }
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();//直接执行被拦截方法 } }
/// <summary> /// 在自定义策略处理器中调用方法 /// </summary> /// <param name="roleArr"></param> /// <returns></returns> public async Task <List <RoleActionModel> > GetRoleAction(Guid [] roleArr) { try { var RoleModuleList = new List <RoleActionModel>(); var Rolelist = await _roleRepositoty.GetAllListAsync(x => roleArr.Contains(x.Id)); //根据Httpcontext存储的角色名称获取角色ID var RoleAssig = await _roleRightAssigRepository.GetAllListAsync(x => Rolelist.Select(s => s.Id).Contains(x.RoleId)); //根据角色ID获取到所有的权限 var Btnlist = await _buttonRepositoty.GetAllListAsync(x => x.IsDrop == false); //获取所有的按钮 List <SysMenu> Menulist = new List <SysMenu>(); if (await _redisCacheManager.Get(Appsettings.app(new string[] { "CacheOptions", "Menukey" }))) //判断菜单缓存是否存在,如果存在则取缓存不存在则取数据库 { Menulist = await _redisCacheManager.GetList <SysMenu>(Appsettings.app(new string[] { "CacheOptions", "Menukey" })); //.Where(x=>MenuIds.Contains(x.Id)).ToList(); } else { Menulist = await this._menuRepositoty.GetAll(x => x.IsDrop == false).AsNoTracking().ToListAsync(); await _redisCacheManager.Set(Appsettings.app(new string[] { "CacheOptions", "Menukey" }), Menulist); } if (!Menulist.Any()) { Menulist = await _menuRepositoty.GetAllListAsync(x => x.IsDrop == false);//根据菜单ID获取菜单列表 x=>MenuIds.Contains(x.Id) } foreach (var item in RoleAssig) { var RoleModel = Rolelist.Where(x => x.Id == item.RoleId).FirstOrDefault(); //获取角色实体 var MenuModel = Menulist.Where(x => x.Id == item.MenuId).FirstOrDefault(); //获取菜单实体 RoleModuleList.Add(new RoleActionModel { RoleName = RoleModel.Id, ActionName = MenuModel.APIAddress }); if (!item.ButtonIds.IsNullOrEmpty()) //判断是否存在按钮 { List <Guid> guids = new List <Guid>(); var btnArr = item.ButtonIds.Split(',').Select(x => x.ToGuid()).ToList(); var RoleBtn = Btnlist.Where(x => btnArr.Contains(x.Id)).ToList(); RoleModuleList.AddRange(RoleBtn.Select(x => new RoleActionModel { RoleName = RoleModel.Id,//在这里代表的是 ActionName = x.APIAddress, })); } } return(RoleModuleList); } catch (Exception ex) { var FromMailAddres = Appsettings.app(new string[] { "FromMailConfig", "FromMailAddres" }); var FromMailPwd = Appsettings.app(new string[] { "FromMailConfig", "FromMailPwd" }); var ToMail = Appsettings.app(new string[] { "FromMailConfig", "ToMail" }); await SendEmail.SendMailAvailableAsync(FromMailAddres, FromMailPwd, ToMail, $"{ DateTime.Now.ToString("yyyy-MM-dd")}Redis超出限制错误", "Redis链接错误"); LogServer.WriteErrorLog($"{ DateTime.Now.ToString("yyyy-MM-dd hh:mm:dd")}Redis超出限制错误", $"Redis链接错误", ex); throw ex; } }
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(); } }
/// <summary> /// 添加用户登录信息 /// </summary> /// <param name="code"></param> /// <returns></returns> public async Task <bool> PostWx_UserOpenIdAsync(string code) { string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxConfig.AppId + "&secret=" + WxConfig.AppSecret + "&js_code=" + code + "&grant_type=authorization_code"; Wx_UserOpenId userLog = new Wx_UserOpenId(); userLog.ID = IdHelper.CreateGuid(); string returnText = WxHelper.GetResponse(url); if (returnText != "") { JObject obj = Newtonsoft.Json.Linq.JObject.Parse(returnText); string openid = obj["openid"].ToString(); string sessionkey = obj["session_key"].ToString(); userLog.OpenId = openid; _redisCacheManager.Remove("myOpenId"); _redisCacheManager.Remove("mySessionKey"); _redisCacheManager.Set("myOpenId", openid, TimeSpan.FromHours(2)); _redisCacheManager.Set("mySessionKey", sessionkey, TimeSpan.FromHours(2)); } userLog.LoginTime = DateTime.Now; var result = 0; return(await Task.Run(() => { var isAny = db.Queryable <Wx_UserOpenId>().Where(it => it.OpenId == userLog.OpenId).Any();//是否存在 if (isAny == false) { result = db.Insertable(userLog).ExecuteCommand(); } else { result = db.Updateable <Wx_UserOpenId>().SetColumns(it => new Wx_UserOpenId() { LoginTime = userLog.LoginTime }) .Where(it => it.OpenId == userLog.OpenId).ExecuteCommand(); } return result > 0; })); }
/// <summary> /// 获取用户的角色权限 /// </summary> /// <param name="userId"></param> /// <returns></returns> private async Task <List <string> > GetRolePermission(string userId) { var key = CacheConstantKey.Create(CacheConstantKey.PERMISSION_ROLE_PERMISSION, userId); if (redisCacheManager.Exists(key)) { return(redisCacheManager.Get(key).Split(",").ToList()); } List <string> userRoles = await GetUserRole(userId); List <string> rolePermissions = new List <string>(); foreach (var item in await sysRolePermissionRepository.QueryAsync(w => userRoles.Contains(w.RoleID.ToString()))) { rolePermissions.Add(item.PermissionID.ToString()); } redisCacheManager.Set(key, string.Join(",", rolePermissions)); return(rolePermissions); }
public async Task <object> Get(int id, int page = 1, string bcategory = "技术博文") { int intTotalCount = 6; int Total = 0; int TotalCount = 1; List <BlogArticle> blogArticleList = new List <BlogArticle>(); using (MiniProfiler.Current.Step("开始加载数据:")) { if (redisCacheManager.Get <object>("Redis.Blog") != null) { MiniProfiler.Current.Step("从Redis服务器中加载数据:"); blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); blogArticleList = await blogArticleServices.Query(a => a.bcategory == bcategory); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } } Total = blogArticleList.Count(); TotalCount = blogArticleList.Count() / intTotalCount; using (MiniProfiler.Current.Step("获取成功后,开始处理最终数据")) { blogArticleList = blogArticleList.OrderByDescending(d => d.bID).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList(); foreach (var item in blogArticleList) { if (!string.IsNullOrEmpty(item.bcontent)) { item.bRemark = (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Length >= 200 ? (HtmlHelper.ReplaceHtmlTag(item.bcontent)).Substring(0, 200) : (HtmlHelper.ReplaceHtmlTag(item.bcontent)); int totalLength = 500; if (item.bcontent.Length > totalLength) { item.bcontent = item.bcontent.Substring(0, totalLength); } } } } return(Ok(new { success = true, page = page, total = Total, pageCount = TotalCount, data = blogArticleList })); }
/// <summary> /// 菜单表任何操作将缓存重置 /// </summary> public async Task RestMenuCache() { try { _redisCacheManager.Remove("Menu"); var list = await this._menuRepositoty.GetAll(x => x.IsDrop == false).AsNoTracking().ToListAsync(); _redisCacheManager.Set("Menu", list); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取微信用户openid /// </summary> /// <param name="code"></param> /// <returns></returns> public static string GetOpenId(string code) { string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxConfig.AppId + "&secret=" + WxConfig.AppSecret + "&js_code=" + code + "&grant_type=authorization_code"; WebClient wc = new System.Net.WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; wc.Encoding = Encoding.UTF8; string returnText = wc.DownloadString(url); if (returnText.Contains("errcode")) { //可能发生错误 } JObject obj = Newtonsoft.Json.Linq.JObject.Parse(returnText); string openid = obj["openid"].ToString(); string sessionkey = obj["session_key"].ToString(); _redisCacheManager.Remove("myOpenId"); _redisCacheManager.Remove("mySessionKey"); _redisCacheManager.Set("myOpenId", openid, TimeSpan.FromHours(2)); _redisCacheManager.Set("mySessionKey", sessionkey, TimeSpan.FromHours(2)); return(openid); }
/// <summary> /// 创建组对象 /// </summary> /// <returns></returns> public async override Task OnConnectedAsync() { if (Context.User.Claims.Any()) { var Id = Context.User.Claims.FirstOrDefault(x => x.Type == "Id").Value.ToGuid(); var name = Context.User.Claims.FirstOrDefault(x => x.Type == "userName").Value.ToGuid(); var model = new SignalRModel { UserId = Id, SignalRConnectionId = Context.ConnectionId }; _redisCacheManager.Set(Id.ToString(), model, TimeSpan.Parse("1230"));//将用户关联的ConnectionID放到缓存中 } await base.OnConnectedAsync(); }
public async Task <List <BlogArticle> > GetBlogs() { List <BlogArticle> blogs = new List <BlogArticle>(); if (_redisCacheManager.Get <object>("Redis.Blog") != null) { blogs = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogs = await _blogArticleServices.Query(d => d.BId > 5); _redisCacheManager.Set("Redis.Blog", blogs, TimeSpan.FromHours(2));//缓存2小时 } return(blogs); }
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> /// <param name="roleArr"></param> /// <returns></returns> public async Task <List <RoleActionModel> > GetRoleAction(Guid [] roleArr) { var RoleModuleList = new List <RoleActionModel>(); var Rolelist = await _roleRepositoty.GetAllListAsync(x => roleArr.Contains(x.Id)); //根据Httpcontext存储的角色名称获取角色ID var RoleAssig = await _roleRightAssigRepository.GetAllListAsync(x => Rolelist.Select(s => s.Id).Contains(x.RoleId)); //根据角色ID获取到所有的权限 var Btnlist = await _buttonRepositoty.GetAllListAsync(x => x.IsDrop == false); //获取所有的按钮 List <SysMenu> Menulist = new List <SysMenu>(); if (await _redisCacheManager.Get(Appsettings.app(new string[] { "CacheOptions", "Menukey" }))) //判断菜单缓存是否存在,如果存在则取缓存不存在则取数据库 { Menulist = await _redisCacheManager.GetList <SysMenu>(Appsettings.app(new string[] { "CacheOptions", "Menukey" })); //.Where(x=>MenuIds.Contains(x.Id)).ToList(); } else { Menulist = await this._menuRepositoty.GetAll(x => x.IsDrop == false).AsNoTracking().ToListAsync(); await _redisCacheManager.Set(Appsettings.app(new string[] { "CacheOptions", "Menukey" }), Menulist); } if (!Menulist.Any()) { Menulist = await _menuRepositoty.GetAllListAsync(x => x.IsDrop == false);//根据菜单ID获取菜单列表 x=>MenuIds.Contains(x.Id) } foreach (var item in RoleAssig) { var RoleModel = Rolelist.Where(x => x.Id == item.RoleId).FirstOrDefault(); //获取角色实体 var MenuModel = Menulist.Where(x => x.Id == item.MenuId).FirstOrDefault(); //获取菜单实体 RoleModuleList.Add(new RoleActionModel { RoleName = RoleModel.Id, ActionName = MenuModel.APIAddress }); if (!item.ButtonIds.IsNullOrEmpty()) //判断是否存在按钮 { List <Guid> guids = new List <Guid>(); var btnArr = item.ButtonIds.Split(',').Select(x => x.ToGuid()).ToList(); var RoleBtn = Btnlist.Where(x => btnArr.Contains(x.Id)).ToList(); RoleModuleList.AddRange(RoleBtn.Select(x => new RoleActionModel { RoleName = RoleModel.Id,//在这里代表的是 ActionName = x.APIAddress, })); } } return(RoleModuleList); }
public async Task <List <BlogArticle> > GetBlogs() { //var connect = Appsettings.app(new string[] {"Appsettings", "RedisCaching", "ConnectionString" }); List <BlogArticle> blogs = new List <BlogArticle>(); if (_redisCache.Get <object>("Redis.LSBlog") != null) { blogs = _redisCache.Get <List <BlogArticle> >("Redis.LSBlog"); } else { blogs = await _dal.getBlogs(); _redisCache.Set("Redis.LSBlog", blogs, System.TimeSpan.FromHours(3)); } return(blogs); }
public async Task <List <UserInfo> > Get() { //得到Readis配置连接 var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); //查询数据 var userinfoList = await UserInfoServices.GetUserInfoList(); if (RedisCacheManager.Get <object>("redis") != null) { RedisCacheManager.Get <List <UserInfo> >("redis"); } else { RedisCacheManager.Set("redis", userinfoList, TimeSpan.FromHours(2)); } return(userinfoList); }
public async Task <IActionResult> GetAllUserByRedis(int id) { var key = $"Redis{id}"; User user = new User(); if (_redisCacheManager.Get <object>(key) != null) { user = _redisCacheManager.Get <User>(key); } else { user = await _userService.GetById(id); _redisCacheManager.Set(key, user, TimeSpan.FromHours(2)); //设置缓存,缓存2小时 } return(Ok(user)); }
public async Task <List <BlogArticle> > GetBlogs() { //var connect = Appsettings.app(new string []{ "AppSettings", "RedisCaching", "ConnectionString"});//按照层级的顺序,依次写出来 List <BlogArticle> blogArticlesList = new List <BlogArticle>(); //if (redisCacheManager.Get<object>("Redis.Blog") != null) //{ // blogArticlesList = redisCacheManager.Get<List<BlogArticle>>("Redis.Blog"); //} //else //{ blogArticlesList = await blogArticleServices.Query(d => d.bID < 5); redisCacheManager.Set("Redis.Blog", blogArticlesList, TimeSpan.FromHours(2)); //缓存2小时 //} return(blogArticlesList); }
public async Task <List <Advertisement> > Get(int id) { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 var advertisementList = new List <Advertisement>(); if (redisCacheManager.Get <object>("Redis.Doctor") != null) { advertisementList = redisCacheManager.Get <List <Advertisement> >("Redis.Doctor"); } else { advertisementList = await advertisementServices.Query(d => d.Id == id); redisCacheManager.Set("Redis.Doctor", advertisementList, TimeSpan.FromHours(2)); } return(advertisementList); }
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 <List <BlogArticle> > GetBlogs() { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); var blogArticleList = new List <BlogArticle>(); if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.Query(s => s.bID > 5); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } return(blogArticleList); }
public async Task <List <BlogArticle> > GetBlogs() { // 获取配置信息 var con = _options.Value.RedisCaching.ConnectionString; // var connect = AppsettingsHelper.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); List <BlogArticle> blogArticles = new List <BlogArticle>(); if (_redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticles = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticles = await _blogArticleServices.GetBlogs(); _redisCacheManager.Set("Redis.Blog", blogArticles, TimeSpan.FromHours(2)); } return(blogArticles); }
//[Authorize(Policy = "SystemOrAdmin")] //[ApiExplorerSettings(GroupName = "V1")] //[CustomRoute(ApiVersions.V2, "Get")] public async Task <PageModel <BlogArticle> > Get(int id, int page = 1) { //每页大小 var pageSize = 10; //var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <BlogArticle> blogArticleList = new List <BlogArticle>(); blogArticleList = await _blogArticleServices.GetBlogs(); // 你可以用这种包括的形式 using (MiniProfiler.Current.Step("开始加载数据:")) { //先查找Redis缓存中有没有这个数据,有就直接带出来,不需要做DB操作,没有的话更新缓存,缓存时间为2小时 if (_redisCacheManager.Get <object>("Redis.Blog") != null) { // 也可以直接这么写 MiniProfiler.Current.Step("从Redis服务器中加载数据:"); blogArticleList = _redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { // 也可以直接这么写 MiniProfiler.Current.Step("从MSSQL服务器中加载数据:"); blogArticleList = await _blogArticleServices.GetBlogs(); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } MiniProfiler.Current.Step("处理成功之后,开始处理最终数据:"); var pageModel = new PageModel <BlogArticle> { page = page, pageCount = (blogArticleList.Count + pageSize - 1) / pageSize, dataCount = blogArticleList.Count, PageSize = pageSize, data = blogArticleList.Skip((page - 1) * pageSize).Take(pageSize).ToList(), success = true }; //blogArticleList = await _blogArticleServices.GetBlogs(); //_redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 return(pageModel); } }
public async Task <List <Advertisement> > GetBlogs() { //var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <Advertisement> blogArticleList = new List <Advertisement>(); if (_redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = _redisCacheManager.Get <List <Advertisement> >("Redis.Blog"); } else { blogArticleList = await _advertisementServices.Query(d => d.Id == 1); _redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } return(await _advertisementServices.GetBlogs()); }
public async Task <List <BlogArticle> > GetBlogs() { var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来 List <BlogArticle> blogArticleList = new List <BlogArticle>(); //Controller使用Redis缓存 if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.getBlogs(); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));//缓存2小时 } return(blogArticleList); }
public async Task <object> Get(int id, int page = 1, string bcategory = "技术博文") { int intTotalCount = 6; int TotalCount = 1; List <BlogArticle> blogArticleList = new List <BlogArticle>(); if (redisCacheManager.Get <object>("Redis.Blog") != null) { blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticleList = await blogArticleServices.Query(a => a.bcategory == bcategory); redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2)); } TotalCount = blogArticleList.Count() / intTotalCount; blogArticleList = blogArticleList.OrderByDescending(d => d.bID).Skip((page - 1) * intTotalCount).Take(intTotalCount).ToList(); foreach (var item in blogArticleList) { if (!string.IsNullOrEmpty(item.bcontent)) { //item.bcontent = Tools.ReplaceHtmlTag(item.bcontent); int totalLength = 500; if (item.bcontent.Length > totalLength) { item.bcontent = item.bcontent.Substring(0, totalLength); } } } var data = new { success = true, page = page, pageCount = TotalCount, data = blogArticleList }; return(data); }
public async Task <List <BlogArticle> > getBlogs() { var connetct = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); List <BlogArticle> blogArticles = new List <BlogArticle>(); if (redisCacheManager.Get <Object>("Redis.Blog") != null) { blogArticles = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog"); } else { blogArticles = await this.blogArticleServices.getBlogs(); redisCacheManager.Set("Redis.Blog", blogArticles, TimeSpan.FromHours(2)); } return(blogArticles); }