public async Task OnExecuteAsync(Func <string, string, Task> processMessageAsync)
        {
            string prevValue    = null;
            string currentValue = null;

            if (await _service.KeyExistsAsync(_lastValueKeyName))
            {
                prevValue = await _service.GetAsync(_lastValueKeyName);
            }

            if (await _service.KeyExistsAsync(_attribute.ChannelOrKey))
            {
                currentValue = await _service.GetAsync(_attribute.ChannelOrKey);
            }

            bool hadValue = !string.IsNullOrEmpty(prevValue);
            bool hasValue = !string.IsNullOrEmpty(currentValue);

            if ((hadValue || hasValue) && currentValue != prevValue)
            {
                // set value for comparison next check
                await _service.SetAsync(_lastValueKeyName, currentValue);

                // process the value since it has changed
                await processMessageAsync(prevValue, currentValue);
            }
        }
Exemple #2
0
        public async Task <TokenInfo> RefreshTokenAsync(string refreshToken)
        {
            var tokenKey  = _tokenKeyPattern + refreshToken;
            var tokenInfo = await _redisService.GetAsync <TokenInfo>(tokenKey);

            if (tokenInfo == null)
            {
                return(default);
        public async Task GetSetRedisAsyncTest()
        {
            var testClass = new MyClass()
            {
                Name = "Ali Alp",
                Age  = 38
            };

            await _redisService.SetAsync(testClass.Name, testClass, new CacheOptions()
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(2)
            });

            var result = await _redisService.GetAsync <MyClass>(testClass.Name);

            await _redisService.RemoveAsync(testClass.Name);

            Assert.Equal(testClass.Name, result.Name);
            Assert.Equal(testClass.Age, result.Age);
        }
        public async Task <T> GetAsync <T>(string key, Func <T, Task <T> > action) where T : class, new()
        {
            var result      = new T();
            var cacheResult = await _redisService.GetAsync(key);

            if (String.IsNullOrEmpty(cacheResult))
            {
                //Cache data not found or expired
                result = await action(result);

                if (result != null)
                {
                    await _redisService.SetAsync(key, JsonConvert.SerializeObject(result));
                }
            }
            else
            {
                //Pull from Cache
                result = JsonConvert.DeserializeObject <T>(cacheResult);
            }
            return(result);
        }
Exemple #5
0
        /// <summary>
        /// 判断token是否有效
        /// </summary>
        /// <param name="sToken">token</param>
        /// <returns></returns>
        public async Task <bool> IsToken(string sToken)
        {
            User user = TokenService.TokenGetUser(sToken);

            if (user == null)
            {
                return(false);
            }
            string sRedisToken = await RedisService.GetAsync <string>(CommentConfig.UserToken + user.ID, () => null);

            if (string.IsNullOrWhiteSpace(sRedisToken))
            {
                return(false);
            }
            if (GlobalsConfig.Configuration[ConfigurationKeys.Token_IsSignIn].ToLower() == "true")
            {
                if (sRedisToken != sToken)
                {
                    return(false);
                }
            }
            return(true);
        }
        public async Task <ReturnResult> GetPrice(string symbol)
        {
            Price price = await RedisService.GetAsync(CommentConfig.Price + symbol, () => new Price());

            return(new ReturnResult(ReturnResultStatus.Succeed, price.price));
        }
 /// <summary>
 /// 获取图片验证码,不存在返回空
 /// </summary>
 /// <param name="sCodeKey">密匙Key</param>
 /// <returns></returns>
 public async Task <string> GetImage(string sCodeKey)
 {
     return(await RedisService.GetAsync <string>(CommentConfig.ImageCacheCode + sCodeKey, () => null));
 }
Exemple #8
0
        public async Task <IActionResult> Get(string key, CancellationToken token)
        {
            var person = await _redisService.GetAsync <Person>(key, token);

            return(Ok(person));
        }
        /// <summary>
        /// 身份验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            //不允许匿名访问逻辑
            if (context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowAnonymousAttribute))
            {
                return;
            }
            //判断是否开启权限验证
            if (GlobalsConfig.Configuration[ConfigurationKeys.Verification_Token].ToLower() == "false")
            {
                return;
            }
            //从http请求的头里面获取身份验证信息,验证Jwt
            string sAuthorization = context.HttpContext.Request.Headers["Authorization"].ToString();

            if (string.IsNullOrWhiteSpace(sAuthorization))
            {
                context.Result = new ObjectResult(new ReturnResult()
                {
                    Status  = (int)ReturnResultStatus.UnLogin,
                    Message = "获取不到token"
                });
                return;
            }
            string sToken = sAuthorization.Substring("Bearer ".Length).Trim();

            if (string.IsNullOrWhiteSpace(sToken))
            {
                context.Result = new ObjectResult(new ReturnResult()
                {
                    Status  = (int)ReturnResultStatus.UnLogin,
                    Message = "获取不到token"
                });
                return;
            }
            User user = TokenService.TokenGetUser(sToken);

            if (user == null)
            {
                context.Result = new ObjectResult(new ReturnResult()
                {
                    Status  = (int)ReturnResultStatus.UnLogin,
                    Message = "获取不到token"
                });
                return;
            }
            string sRedisToken = await RedisService.GetAsync <string>(CommentConfig.UserToken + user.ID, () => null);

            if (string.IsNullOrWhiteSpace(sRedisToken))
            {
                context.Result = new ObjectResult(new ReturnResult()
                {
                    Status  = (int)ReturnResultStatus.UnLogin,
                    Message = "获取不到token"
                });
                return;
            }

            if (GlobalsConfig.Configuration[ConfigurationKeys.Token_IsSignIn].ToLower() == "true")
            {
                if (sRedisToken != sToken)
                {
                    context.Result = new ObjectResult(new ReturnResult()
                    {
                        Status  = (int)ReturnResultStatus.UnLogin,
                        Message = "获取不到token"
                    });
                    return;
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// OAuth验证并获取token
        /// </summary>
        /// <param name="IsToken">是否需要更新token</param>
        /// <param name="RedisService">Redis类接口</param>
        /// <returns></returns>
        public static async Task <string> OAuth(bool IsToken, IRedisService RedisService)
        {
            if (await RedisService.ExistsAsync(CommentConfig.MDM_Token) && !IsToken)
            {
                return((await RedisService.GetAsync <string>(CommentConfig.MDM_Token, () => null)).ToString());
            }
            string retString = string.Empty;

            while (true)
            {
                //基本参数
                OAuthBase oAuth = new OAuthBase();
                Dictionary <string, string> dic = new Dictionary <string, string>()
                {
                    { "realm", IphoneServiceKey.Realm },
                    { "oauth_consumer_key", IphoneServiceKey.Consumer_key },
                    { "oauth_token", IphoneServiceKey.Access_token },
                    { "oauth_signature_method", IphoneServiceKey.Oauth_signature_method }
                };
                string timeStamp = oAuth.GenerateTimeStamp();
                string nonce     = oAuth.GenerateNonce();

                #region 签名
                //签名
                string sSign = oAuth.GenerateSignature(
                    url: new Uri(dic["realm"]),
                    callback: null,
                    consumerKey: dic["oauth_consumer_key"],
                    consumerSecret: IphoneServiceKey.Consumer_secret,
                    token: dic["oauth_token"],
                    tokenSecret: IphoneServiceKey.Access_secret,
                    httpMethod: "GET",
                    timeStamp: timeStamp,
                    nonce: nonce,
                    signatureType: OAuthBase.SignatureTypes.HMACSHA1,
                    verifier: null,
                    normalizedUrl: out string normalizedUrl,
                    normalizedRequestParameters: out string normalizedRequestParameters);
                #endregion

                dic.Add("oauth_signature", sSign);
                dic.Add("oauth_timestamp", timeStamp);
                dic.Add("oauth_nonce", nonce);
                dic.Add("oauth_version", "1.0");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mdmenrollment.apple.com/session");
                request.Method = "GET";
                string Headers = null;
                //请求头
                foreach (var temp in dic)
                {
                    Headers += $"{temp.Key}=\"{temp.Value}\",";
                }
                Headers = Headers.Substring(0, Headers.ToString().Length - 1);

                request.Headers.Set("Authorization", $"OAuth {Headers}");
                try
                {
                    HttpWebResponse response         = (HttpWebResponse)request.GetResponse();
                    Stream          myResponseStream = response.GetResponseStream();
                    StreamReader    streamReader     = new StreamReader(myResponseStream);
                    retString = streamReader.ReadToEnd();
                    streamReader.Close();
                    myResponseStream.Close();
                    break;
                }
                catch (Exception ex)
                {
                    Thread.Sleep(30000);
                    string message = ex.Message;
                }
            }
            await RedisService.SetAsync(CommentConfig.MDM_Token, retString, 1);

            return(retString);
        }
 public async Task <string> Get(string key)
 => await _redisService.GetAsync(key);