/// <inheritdoc /> /// <summary> /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.Request.Method == HttpMethod.Get) { //5min降级时间 var b = ThrottlingHelper.ThrottlingDegrade(ConfigHelper.GetIntValue("Throttling"), 300); //当开启动态降级 if (b) { var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName; var actionName = actionContext.ActionDescriptor.ActionName; var item = GetKey(controllerName, actionName, actionContext.ActionArguments); var bRes = MemoryCacheHelper.Get(item); if (bRes != null) { var bResult = (ResponseResult)bRes; if (DateTimeOffset.Now.DateTime <= bResult.Expires.DateTime) { var res = actionContext.Request.CreateResponse(); res.Headers.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(180), Public = true, NoCache = false }; res.Content = new StringContent(bResult.ResponseContent, Encoding.UTF8, "application/json"); actionContext.Response = res; } } } } base.OnActionExecuting(actionContext); }
public IActionResult QueryCsds() { string toekn = ""; //string url1 = ""; //var result1 = HttpClient.HttpPostWeChatApi(url1, ""); //LogOperation.WriteLog(result1); if (MemoryCacheHelper.Exists("access_token")) { toekn = MemoryCacheHelper.Get("access_token").ToString(); } else { var tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx878696657f714582&secret=313ed037bf4e927a6d225317e775d1b9"; var bupo = HttpClient.HttpPostWeChatApi(tokenUrl, JsonConvert.SerializeObject(new { })); TokenDto info = JsonConvert.DeserializeObject <TokenDto>(bupo); toekn = info.access_token; MemoryCacheHelper.Set("access_token", toekn, TimeSpan.FromMinutes(60)); } //参数 string postdata = JsonConvert.SerializeObject(new { }); string url = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=" + toekn; var result = HttpClient.HttpPostWeChatApi(url, postdata); return(Ok(result)); }
public T Get <T>(string key) { switch (_CacheOptions.CacheMediaType) { case CacheMediaType.Local: return(MemoryCacheHelper.Get <string, T>(key)); case CacheMediaType.Redis: try { var redisResult = GetRedisCacheProvider().Get(key); if (!string.IsNullOrEmpty(redisResult)) { return(JsonConvert.DeserializeObject <T>(redisResult)); } } catch (ArgumentException argEx) { throw argEx; } return(default(T)); default: return(default(T)); } }
public static TValue GetSet <TValue>(string script, Func <TValue> func) { var hashKey = script.GetHashCode(); var expired = TimeSpan.FromMinutes(15); var triggerScriptInCache = MemoryCacheHelper.Get <int, TValue>(hashKey); if (triggerScriptInCache == null) { triggerScriptInCache = MemoryCacheHelper.Put <int, TValue>(hashKey, func(), expired); } return(triggerScriptInCache); }
public static T Get <T>(DbContext dbContext, string key) { switch (dbContext.CacheMediaType) { case CacheMediaType.Local: return(MemoryCacheHelper.Get <string, T>(key)); case CacheMediaType.Redis: return(default(T)); default: return(default(T)); } }
private object RuleCaches() { string key = MemoryCacheHelper.GetRuleCaches; if (MemoryCacheHelper.Exists(key)) { return(MemoryCacheHelper.Get(key)); } else { var result = DC.Set <VOS_Rule>().ToList(); MemoryCacheHelper.Set(key, result, new TimeSpan(7, 0, 0, 0)); return(result); } }
/// <summary> /// 读取表缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public ConcurrentDictionary <string, T> Get <T>() where T : IEntity { string tableKey = typeof(T).Name; var result = MemoryCacheHelper.Get <T>(tableKey); if (result == null) { DapperHelper.SQLLiteSession((con, trans) => { AddTableCache <T>(con, trans); }); result = MemoryCacheHelper.Get <T>(tableKey); } return(result); }
public async Task <ApiResult <List <SysMenuDto> > > GetAuthMenuAsync() { var res = new ApiResult <List <SysMenuDto> >(); var auth = await HttpContext.AuthenticateAsync(); var userID = auth.Principal.Identities.First(u => u.IsAuthenticated).FindFirst(ClaimTypes.Sid).Value; res.data = MemoryCacheHelper.Get <List <SysMenuDto> >(KeyModel.AdminMenu + "_" + userID); if (res.data == null) { res.statusCode = (int)ApiEnum.URLExpireError; res.msg = "Session已过期,请重新登录"; } return(res); }
/// <inheritdoc /> /// <summary> /// /// </summary> /// <param name="actionExecutedContext"></param> public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Request.Method == HttpMethod.Get) { if (actionExecutedContext.Response.IsSuccessStatusCode) { var controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; actionExecutedContext.Response.Headers.TryGetValues(CacheConstants.DegradationHttpHeader, out var dCache); var cacheList = (dCache ?? new List <string>()).ToList(); var res = cacheList.Count > 0 ? cacheList[0] : actionExecutedContext.Response.Content.ReadAsStringAsync().Result; var item = GetKey(controllerName, actionName, actionExecutedContext.ActionContext.ActionArguments); var result = new ResponseResult { Expires = DateTimeOffset.Now.AddSeconds(Duration), ResponseContent = res }; var bRes = MemoryCacheHelper.Get(item); if (bRes != null) { var bResult = (ResponseResult)bRes; if (DateTimeOffset.Now.DateTime > bResult.Expires.DateTime) { MemoryCacheHelper.Set(item, result, TimeSpan.FromSeconds(Duration)); } } else { MemoryCacheHelper.Set(item, result, TimeSpan.FromSeconds(Duration)); } if (actionExecutedContext.Response.Headers.Contains(CacheConstants.DegradationHttpHeader)) { actionExecutedContext.Response.Headers.Remove(CacheConstants.DegradationHttpHeader); } //设置响应缓存30s if (actionExecutedContext.Response.Headers.CacheControl == null) { actionExecutedContext.Response.Headers.CacheControl = new CacheControlHeaderValue(); } actionExecutedContext.Response.Headers.CacheControl.MaxAge = TimeSpan.FromSeconds(30); actionExecutedContext.Response.Headers.CacheControl.Public = true; actionExecutedContext.Response.Headers.CacheControl.NoCache = false; } } base.OnActionExecuted(actionExecutedContext); }
public void PersoneProcces(JObject person) { var personImage = (JArray)person["user"]["photos"]; var personId = (string)person["user"]["_id"]; // Like(personId); var personCache = _cacheHelper.Get <JObject>(personId.ToString()); if (personCache.IsNullOrEmpty()) { _cacheHelper.Set("personId", person); SavePersoneImage(personImage, personId); } else { SavePersoneImage(personImage, personId); } }
public async Task <List <GetStudentByIdDto> > QuerysByClassNo(GetStudentByIdInput input) { var key = "QuerysByClassNo-" + input.ClassNo; if (MemoryCacheHelper.Exists(key)) { var list = MemoryCacheHelper.Get(key); return((List <GetStudentByIdDto>)list); } else { var students = await _studentService.QueryStudentsByClassNo(input); MemoryCacheHelper.Set(key, students, TimeSpan.FromMinutes(1)); return(students); } }
public List <SimpleShop2> GetCacheList2() { List <SimpleShop2> list = new List <SimpleShop2>(); MemoryCacheHelper mc = new MemoryCacheHelper(); object obj = mc.Get(Ace.Globals.CacheShop2); if (obj != null) { list = obj as List <SimpleShop2>; } else { list = this.DbContext.Query <Shop>().Select(a => new SimpleShop2() { ShopID = a.ID, ShopName = a.ShopName }).ToList(); mc.Set(Ace.Globals.CacheShop2, list, System.TimeSpan.FromMinutes(30), true);//缓存30分钟 自动延长 } return(list); }
/// <summary> /// Get Configs /// </summary> /// <returns></returns> private static IEnumerable <T> GetConfigs() { //modifyTime reagard as config version DateTime configDbVersion = ModifyTime; //if memory cache exist if (MemoryCacheHelper.Exist(versionCacheKey) && MemoryCacheHelper.Exist(versionCacheKey)) { //if cache version >= db version,cache is available. if (Convert.ToDateTime(MemoryCacheHelper.Get <int, DateTime>(versionCacheKey)) >= configDbVersion) { return(MemoryCacheHelper.Get <int, IEnumerable <T> >(configCacheKey)); } } //if memory cache not exist var dbConfig = GetConfigsFromDb(); MemoryCacheHelper.Put(configCacheKey, dbConfig); MemoryCacheHelper.Put(versionCacheKey, configDbVersion); return(dbConfig); }
public IActionResult GetUserInfo(string openId) { //参数 string postdata = JsonConvert.SerializeObject(new { }); //---------第一步------------ //appid=wx878696657f714582 //secret=313ed037bf4e927a6d225317e775d1b9 //---------第二步------------ //获取access_token值 string toekn = ""; if (MemoryCacheHelper.Exists("access_token")) { toekn = MemoryCacheHelper.Get("access_token").ToString(); } else { var tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx878696657f714582&secret=313ed037bf4e927a6d225317e775d1b9"; var bupo = HttpClient.HttpPostWeChatApi(tokenUrl, postdata); TokenDto info = JsonConvert.DeserializeObject <TokenDto>(bupo); toekn = info.access_token; MemoryCacheHelper.Set("access_token", toekn, TimeSpan.FromMinutes(60)); } //---------第三步------------ //获取openId值 if (string.IsNullOrEmpty(openId)) { openId = "oXriy6Dh8McEmYtZJx4xr6GABuvU"; } //---------第四步------------ //获取用户基本信息 string url = " https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + toekn + "&openid=" + openId + "&lang=zh_CN"; var user = HttpClient.HttpPostWeChatApi(url, postdata); return(Ok(user)); }
public IActionResult InsertCsd() { string toekn = ""; if (MemoryCacheHelper.Exists("access_token")) { toekn = MemoryCacheHelper.Get("access_token").ToString(); } else { var tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx878696657f714582&secret=313ed037bf4e927a6d225317e775d1b9"; var bupo = HttpClient.HttpPostWeChatApi(tokenUrl, JsonConvert.SerializeObject(new { })); TokenDto info = JsonConvert.DeserializeObject <TokenDto>(bupo); toekn = info.access_token; MemoryCacheHelper.Set("access_token", toekn, TimeSpan.FromMinutes(60)); } //参数 string postdata = JsonConvert.SerializeObject(new { kf_account = "test1@test", nickname = "客服1", password = "******" }); string url = " https://api.weixin.qq.com/customservice/kfaccount/add?access_token=" + toekn; var result = HttpClient.HttpPostWeChatApi(url, postdata); return(Ok(result)); }
public IActionResult GetUserInfos() { //参数 string postdata = JsonConvert.SerializeObject(new { }); string token = ""; if (MemoryCacheHelper.Exists("access_token")) { token = MemoryCacheHelper.Get("access_token").ToString(); } else { var tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx878696657f714582&secret=313ed037bf4e927a6d225317e775d1b9"; var bupo = HttpClient.HttpPostWeChatApi(tokenUrl, postdata); TokenDto tokenInfo = JsonConvert.DeserializeObject <TokenDto>(bupo); token = tokenInfo.access_token; MemoryCacheHelper.Set("access_token", token, TimeSpan.FromMinutes(60)); } string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token + "&next_openid="; var user = HttpClient.HttpPostWeChatApi(url, postdata); return(Ok(user)); }
public static IUserToken Get(string ID) { return(_session.Get(ID)); }
public T Get <T>(string key) { return(MemoryCacheHelper.Get <string, T>(key)); }
public IUserToken Get(string ID) { return(_sessionCache.Get(ID)); }
public ChannelInfo Get(string name) { return(_cache.Get(name)); }
public async Task <ApiResult <string> > Login([FromBody] SysAdminLogin parm) { var apiRes = new ApiResult <string>() { statusCode = (int)ApiEnum.HttpRequestError }; var token = ""; try { #region 1. 从缓存获取公钥私钥解密,再解密密码 //获得公钥私钥,解密 var rsaKey = MemoryCacheHelper.Get <List <string> >(KeyModel.LoginKey); if (rsaKey == null) { apiRes.msg = "登录失败,请刷新浏览器再次登录"; return(apiRes); } //Ras解密密码 var ras = new RSAEncrypt(rsaKey[0], rsaKey[1]); parm.password = ras.Decrypt(parm.password); #endregion #region 2. 判断用户登录次数限制以及过期时间 //获得用户登录限制次数 var configLoginCount = Convert.ToInt32(Appsettings.Configuration[KeyModel.LoginCount]); //获得登录次数和过期时间 SysAdminLoginConfig loginConfig = MemoryCacheHelper.Get <SysAdminLoginConfig>(KeyModel.LoginCount) ?? new SysAdminLoginConfig(); if (loginConfig.Count != 0 && loginConfig.DelayMinute != null) { //说明存在过期时间,需要判断 if (DateTime.Now <= loginConfig.DelayMinute) { apiRes.msg = "您的登录以超过设定次数,请稍后再次登录~"; return(apiRes); } else { //已经过了登录的预设时间,重置登录配置参数 loginConfig.Count = 0; loginConfig.DelayMinute = null; } } #endregion #region 3. 从数据库查询该用户 //查询登录结果 var dbres = _adminService.LoginAsync(parm).Result; if (dbres.statusCode != 200) { //增加登录次数 loginConfig.Count += 1; //登录的次数大于配置的次数,则提示过期时间 if (loginConfig.Count == configLoginCount) { var configDelayMinute = Convert.ToInt32(Appsettings.Configuration[KeyModel.LogindElayMinute]); //记录过期时间 loginConfig.DelayMinute = DateTime.Now.AddMinutes(configDelayMinute); apiRes.msg = "登录次数超过" + configLoginCount + "次,请" + configDelayMinute + "分钟后再次登录"; return(apiRes); } //记录登录次数,保存到session MemoryCacheHelper.Set(KeyModel.LoginCount, loginConfig); //提示用户错误和登录次数信息 apiRes.msg = dbres.msg + " 您还剩余" + (configLoginCount - loginConfig.Count) + "登录次数"; return(apiRes); } #endregion #region 4. 设置Identity User信息 var user = dbres.data.admin; var identity = new ClaimsPrincipal( new ClaimsIdentity(new[] { new Claim(ClaimTypes.Sid, user.ID), new Claim(ClaimTypes.Role, user.RoleId), new Claim(ClaimTypes.Thumbprint, user.HeadPic), new Claim(ClaimTypes.Name, user.RelName), new Claim(ClaimTypes.WindowsAccountName, user.Account), new Claim(ClaimTypes.UserData, user.LastLoginTime.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme) ); if (Appsettings.Configuration[KeyModel.LoginSaveUser] == "Session") {//如果保存用户类型是Session,则默认设置cookie退出浏览器 清空,并且保存用户信息 await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { AllowRefresh = false }); } else { //根据配置保存浏览器用户信息,小时单位 var hours = int.Parse(Appsettings.Configuration[KeyModel.LoginCookieExpires]); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identity, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddHours(hours), IsPersistent = true, AllowRefresh = false }); } #endregion #region 5. 保存权限信息到缓存 if (dbres.data.menu != null) { var menuSaveType = Appsettings.Configuration[KeyModel.LoginAuthorize]; if (menuSaveType == "Redis") { RedisCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } else { MemoryCacheHelper.Set(KeyModel.AdminMenu + "_" + dbres.data.admin.ID, dbres.data.menu); } } #endregion #region 6. 生成token信息,并且返回给前端 token = JwtHelper.IssueToken(new TokenModel() { UserID = user.ID, UserName = user.RelName, UserAccount = user.Account, Role = "AdminPolicy", ProjectName = "DL.Admin" }); MemoryCacheHelper.Del <string>(KeyModel.LoginKey); MemoryCacheHelper.Del <string>(KeyModel.LoginCount); #endregion #region 7. 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 1, Message = "登录", Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } catch (Exception ex) { apiRes.msg = ex.Message; apiRes.statusCode = (int)ApiEnum.Error; #region 保存日志 var agent = HttpContext.Request.Headers["User-Agent"]; var log = new SysLog() { ID = Guid.NewGuid().ToString(), CreateTime = DateTime.Now, Layer = 4, Message = "登录失败!" + ex.Message, Exception = ex.Message, Url = "/Login/Login", IP = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Account = parm.loginname, Browser = agent.ToString() }; await _logService.AddAsync(log); #endregion } apiRes.statusCode = (int)ApiEnum.Status; apiRes.data = token; return(apiRes); }
public static ActionResult Get(string key) { return(_cache.Get(key)); }
public IActionResult Index() { //var pk = 0; //var j = 8 / pk; List <Demo> list = new List <Demo>(); Demo de = new Demo(); de.Id = 1; de.Name = "1"; de.M = 2; list.Add(de); Demo des = new Demo(); des.Name = "2"; des.Id = 2; des.M = 2; list.Add(des); Demo desd = new Demo(); desd.Name = "1"; desd.Id = 1; desd.M = 2; list.Add(desd); var kli = list.GroupBy(p => new { p.Id, p.Name }).Select(k => new Demo { Id = k.Key.Id, Name = k.Key.Name, M = k.Sum(n => n.M) }).ToList(); var d = DateTime.Now.ToString("dd"); List <int> klist = new List <int>(); klist.Add(1); klist.Add(2); List <int> klists = new List <int>(); var kp = klist.Where(p => p == 1 || p == 2).ToList().Count(); RedisHelper redis = new RedisHelper(12); string str = "wwg123"; redis.StringSet("strKey", str); //var strget = redis.StringGet("strKey"); //Demo demo = new Demo() //{ // Id = 1, // Name = "123" //}; //redis.StringSet("redis_string_model", demo); //var model = redis.StringGet<Demo>("redis_string_model"); // for (int i = 0; i < 10; i++) //{ // redis.StringIncrement("StringIncrement", 2); //} //for (int i = 0; i < 10; i++) //{ // redis.StringDecrement("StringIncrement"); //} //redis.StringSet("redis_string_model1", demo, TimeSpan.FromSeconds(10));//过期时间 //#endregion #region List //for (int i = 0; i < 10; i++) //{ // redis.ListRightPush("list", i); //} //for (int i = 10; i < 20; i++) //{ // redis.ListLeftPush("list", i); //} //var length = redis.ListLength("list"); //var leftpop = redis.ListLeftPop<string>("list"); //var rightPop = redis.ListRightPop<string>("list"); //var list = redis.ListRange<int>("list"); //redis.ListRightPush("listdes", 89); // List<Demo> de = new List<Demo>(); // de.Add(new Demo { Id = 1, Name = "1" }); // de.Add(new Demo { Id = 31, Name = "31" }); // de.Add(new Demo { Id = 21, Name = "21" }); // redis.ListRightPush("listde", de); // redis.StringSet("hlisdts",de); //var listhists= redis.StringGet<List<Demo>>("hlisdts"); #endregion //Thread.Sleep(10000); //Stream s = new FileStream(@"H:\包含\CIB)YET_4S5Z8KRCS(X)9_7.jpg", FileMode.Create); ////Images im = new Images(); //// im.Compress(s); MemoryCacheHelper cache = new MemoryCacheHelper(); //var data = "wenwanguang"; //var key = "key1"; //object temp = _cache.Get(key); //if (temp == null) // cache.Set(key, data, DateTime.Now - DateTime.Now.AddDays(-1), false); //data = "rere"; //temp = _cache.Get(key); //F f = new F(); // var key = "key1"; //object temp = _cache.Get(key); //if (temp == null) // cache.Set(key, f, DateTime.Now - DateTime.Now.AddDays(-1), false); //f.A = "rere"; //temp = _cache.Get(key); string [] data = { "1", "5" }; var key = "key1"; object temp = _cache.Get(key); if (temp == null) { cache.Set(key, data, DateTime.Now - DateTime.Now.AddDays(-1), false); } for (int i = 0; i < data.Length; i++) { data[i] = "d"; } temp = _cache.Get(key); // log.Info("wwg"); LoggerManager.Info("444"); //定时任务 return(View()); }