首页 > 代码库 > 定时请求微信Access_Token

定时请求微信Access_Token

        /// <summary>
        /// 设置缓存并在缓存超时两分钟前重新请求
        /// </summary>
        private void SetAndAutoRefreshAccessToken()
        {
            object oToken = HttpContext.Current.Cache[WxConst.ACCESS_TOKEN];
            string sToken = "";
            int iExpiresIn = 0;
            if (oToken == null)
            {
                sToken = GetAccessToken(out iExpiresIn);

                // 缓存到期前更新缓存
                HttpContext.Current.Cache.Insert(WxConst.ACCESS_TOKEN, sToken, null, DateTime.Now.AddSeconds(iExpiresIn), TimeSpan.Zero,
                    (string key, CacheItemUpdateReason reason, out object expensiveObject, out CacheDependency dependency, out DateTime absoluteExpiration, out TimeSpan slidingExpiration) =>
                    {
                        sToken = GetAccessToken(out iExpiresIn);
                        // 设置缓存有效时间为微信access_token有效斯减120秒
                        iExpiresIn = iExpiresIn - 120;

                        expensiveObject = sToken;
                        dependency = null;
                        absoluteExpiration = DateTime.Now.AddSeconds(iExpiresIn);
                        slidingExpiration = TimeSpan.Zero;
                    }
                    );
            }
        }

 

定时请求微信Access_Token