Exemplo n.º 1
0
        public async Task Invoke(HttpContext context)
        {
            bool validOk = false;

            if (!string.IsNullOrWhiteSpace(option.AuthApiStartWith) && context.Request.Path.ToString().StartsWith(option.AuthApiStartWith))
            {
                StringValues token = StringValues.Empty;

                if (context.Request.Headers.TryGetValue(option.TokenKey, out token))
                {
                    if (await cache.ExistsAsync(token))
                    {
                        validOk = true;
                    }
                }
            }
            else
            {
                validOk = true;
            }


            if (!validOk)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            }
            else
            {
                await next(context);
            }
        }
        private async Task <T> Get <T>(string key)
        {
            var json = string.Empty;

            if (await _distributedCache.ExistsAsync(key))
            {
                json = await _distributedCache.GetCustomValueAsync <string>(key);
            }
            return(JsonConvert.DeserializeObject <T>(json));
        }
        public static async Task <T> GetAsync <T>(this IDistributedCache source, string key, TimeSpan time, Func <Task <T> > fetch) where T : class
        {
            if (await source.ExistsAsync(key))
            {
                return(await source.GetAsync <T>(key));
            }

            var result = await fetch();

            if (result != null)
            {
                var stringToPersist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                var data            = Encoding.UTF8.GetBytes(stringToPersist);

                var options = new DistributedCacheEntryOptions().SetSlidingExpiration(time);
                source.Set(key, data, options);
            }


            return(result);
        }