Exemplo n.º 1
0
        public async Task Invoke(HttpContext context)
        {
            if (!isRequestCachable(context.Request))
            {
                await _next(context);
            }
            else
            {
                var cacheKey        = string.Empty;
                var cacheKeyToLower = string.Empty;
                var req             = context.Request;
                req.EnableBuffering();

                using (StreamReader reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
                {
                    var request = await reader.ReadToEndAsync();

                    cacheKey          = $"{req.Scheme}{req.Host}{req.Path}{req.QueryString}{request}";
                    cacheKeyToLower   = cacheKey.ToLower();
                    req.Body.Position = 0;
                }

                var cachedResponse = await _distributedcache.GetAsync(cacheKeyToLower);

                if (cachedResponse != null)
                {
                    var serializedResponse = Encoding.UTF8.GetString(cachedResponse);
                    this._logger.LogInformation(serializedResponse);
                    await context.Response.WriteAsync(serializedResponse, Encoding.UTF8);

                    return;
                }
                else
                {
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                    {
                        context.Response.Body = responseBody;
                        await _next(context);

                        var response = await FormatResponse(context.Response);

                        await responseBody.CopyToAsync(originalBodyStream);

                        if (context.Response.StatusCode == (int)HttpStatusCode.OK)
                        {
                            var cacheobj = CacheUrlRegister.GetCacheUrlList().Where(item => item.URL.ToLower() == context.Request.Path.ToString().ToLower()).FirstOrDefault();
                            var options  = new DistributedCacheEntryOptions()
                                           .SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheobj.AbsoluteExpirationTimeSpanInseconds))
                                           .SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheobj.SlidingExpirationTimeSpanInseconds));

                            this._logger.LogInformation(response);
                            await _distributedcache.SetAsync(cacheKeyToLower, Encoding.UTF8.GetBytes(response), options);
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
 private Boolean isRequestCachable(HttpRequest request)
 {
     return(request.Method == "GET" && CacheUrlRegister.GetCacheUrlList().Any(item => item.URL.ToLower() == request.Path.Value.ToString().ToLower()));
 }