Esempio n. 1
0
        /// <summary>
        ///  //SSO登陆产生令牌
        /// </summary>
        /// <param name="userSSOInfo"></param>
        /// <returns></returns>

        public async Task <string> AddToken(UserSSOInfo userSSOInfo)
        {
            string token = $"{Guid.NewGuid().ToString()}";
            await _cache.AddAsync(token, userSSOInfo);

            return(token);
        }
Esempio n. 2
0
 /// <summary>
 /// 添加<paramref name="key"/>的缓存<paramref name="value"/>
 /// 并使用<paramref name="dateTime"/>作为绝对缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <param name="dateTime"></param>
 /// <returns></returns>
 public static Task <bool> AddAsync(this ICache cache, string key, object value, DateTime dateTime)
 {
     return(cache.AddAsync(new CacheDescription(key, value)
     {
         AbsoluteExpiration = dateTime
     }));
 }
Esempio n. 3
0
 /// <summary>
 /// 添加<paramref name="key"/>的缓存<paramref name="value"/>
 /// 并使用<paramref name="timeSpan"/>作为绝对缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <param name="timeSpan"></param>
 /// <returns></returns>
 public static Task <bool> AddAsync(this ICache cache, string key, object value, TimeSpan timeSpan)
 {
     return(cache.AddAsync(new CacheDescription(key, value)
     {
         AbsoluteExpirationRelativeToNow = timeSpan
     }));
 }
Esempio n. 4
0
 /// <summary>
 /// 添加<paramref name="key"/>的缓存<paramref name="value"/>
 /// 并使用<paramref name="timeSpan"/>作为滚动缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key"></param>
 /// <param name="timeSpan"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static Task <bool> AddAsync(this ICache cache, string key, TimeSpan timeSpan, object value)
 {
     return(cache.AddAsync(new CacheDescription(key, value)
     {
         SlidingExpiration = timeSpan
     }));
 }
Esempio n. 5
0
 /// <summary>
 /// 使用<paramref name="pairs"/>作为缓存键值对,进行缓存添加
 /// 并以<paramref name="dateTime"/>作为绝对缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="pairs"></param>
 /// <param name="dateTime"></param>
 /// <returns></returns>
 public static Task <IEnumerable <bool> > AddAsync <TValue>(this ICache cache, IDictionary <string, TValue> pairs, DateTime dateTime)
 {
     return(cache.AddAsync(pairs.Select(dic => new CacheDescription(dic.Key, dic.Value)
     {
         AbsoluteExpiration = dateTime
     }).ToArray()));
 }
Esempio n. 6
0
 /// <summary>
 /// 使用<paramref name="pairs"/>作为缓存键值对,进行缓存添加
 /// 并以<paramref name="timeSpan"/>作为滑动缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="timeSpan"></param>
 /// <param name="pairs"></param>
 /// <returns></returns>
 public static Task <IEnumerable <bool> > AddAsync <TValue>(this ICache cache, TimeSpan timeSpan, IDictionary <string, TValue> pairs)
 {
     return(cache.AddAsync(pairs.Select(dic => new CacheDescription(dic.Key, dic.Value)
     {
         SlidingExpiration = timeSpan
     }).ToArray()));
 }
        /// <summary>
        /// This method adds object in the cache using async api
        /// </summary>
        /// <param name="key"> String key to be added in cache</param>
        /// <param name="customer"> Instance of Customer that will be added to cache</param>
        private static void AddObjectToCacheAsynchronous(string key, Customer customer)
        {
            //Adding item asynchronously
            //Another way is by creating a CacheItem  object
            _cache.AddAsync(key, customer).ContinueWith(task => OnItemAdded(key, task));

            // Wait for the callback.
            Thread.Sleep(1000);
        }
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <AddProductCommandResponse> Handle(AddProductCommand request, CancellationToken cancellationToken)
        {
            var productsList = await _cache.RetrieveAsync <List <GetProductsByIdResponse> >("productsList") ?? new List <GetProductsByIdResponse>();

            var product = new GetProductsByIdResponse {
                Id = new Random().Next(), Name = $"Product {Context.GetContextDataValue<string>("culture")}", Amount = 10
            };

            productsList.Add(product);

            await _cache.AddAsync("productsList", productsList, TimeSpan.FromMinutes(1));

            return(await Task.Run(() => new AddProductCommandResponse { ProductId = product.Id }, cancellationToken));
        }
Esempio n. 9
0
        private async Task SyncRemarksAsync()
        {
            Console.WriteLine("Synchronizing remarks...");
            var remarks = await _database.GetCollection <Remark>()
                          .AsQueryable()
                          .ToListAsync();

            var groups = new HashSet <Group>();

            foreach (var remark in remarks)
            {
                if (remark.Group != null)
                {
                    var group = groups.SingleOrDefault(x => x.Id == remark.Group.Id);
                    if (group == null)
                    {
                        group = await _database.GetCollection <Group>()
                                .AsQueryable()
                                .FirstOrDefaultAsync(x => x.Id == remark.Group.Id);

                        if (group == null)
                        {
                            continue;
                        }
                        groups.Add(group);
                    }
                    remark.Group.Criteria = group.Criteria;
                    remark.Group.Members  = group.Members.ToDictionary(x => x.UserId, x => x.Role);
                }
                remark.PositiveVotesCount = remark.Votes?.Count(x => x.Positive) ?? 0;
                remark.NegativeVotesCount = remark.Votes?.Count(x => !x.Positive) ?? 0;
            }

            var usersRemarks = remarks.GroupBy(x => x.Author.UserId);

            foreach (var userRemarks in usersRemarks)
            {
                await _cache.AddManyToSetAsync($"users:{userRemarks.Key}:remarks",
                                               userRemarks.Select(x => x.Id.ToString()));
            }

            var latestRemarks = remarks.OrderByDescending(x => x.CreatedAt).Take(100);

            foreach (var remark in latestRemarks)
            {
                await _cache.AddToSortedSetAsync("remarks-latest", remark.Id.ToString(), 0, limit : 100);
            }
            foreach (var remark in remarks)
            {
                await _cache.AddAsync($"remarks:{remark.Id}", remark);

                await _cache.GeoAddAsync($"remarks", remark.Location.Longitude,
                                         remark.Location.Latitude, remark.Id.ToString());
            }
            Console.WriteLine("Synchronizing remarks has completed.");
        }
Esempio n. 10
0
        private async Task StoreInCacheAsync <T>(Maybe <T> value, string endpoint, string cacheKey = null,
                                                 TimeSpan?expiry = null) where T : class
        {
            if (endpoint.Empty())
            {
                throw new ArgumentException("Endpoint can not be empty.");
            }
            if (value.HasNoValue)
            {
                return;
            }

            cacheKey = GetCacheKey(endpoint, cacheKey);
            var cacheExpiry = expiry ?? _settings.CacheExpiry;
            await _cache.AddAsync(cacheKey, value.Value, cacheExpiry);
        }
Esempio n. 11
0
        private async Task StoreInCacheAsync <T>(Maybe <T> value, string endpoint, string cacheKey = null,
                                                 TimeSpan?expiry = null) where T : class
        {
            if (endpoint.Empty())
            {
                throw new ArgumentException("Endpoint can not be empty.");
            }
            if (value.HasNoValue)
            {
                return;
            }

            cacheKey = GetCacheKey(endpoint, cacheKey);
            var cacheExpiry = expiry ?? _settings.CacheExpiry;

            Logger.Debug($"Store data in cache, type: {typeof(T).Name}, endpoint: {endpoint}, cacheKey: {cacheKey}, expiry: {expiry}");
            await _cache.AddAsync(cacheKey, value.Value, cacheExpiry);
        }
Esempio n. 12
0
        public async Task AddAsync(Remark remark, bool addGeo = false, bool addLatest = false)
        {
            if (remark.Group != null)
            {
                var group = await _groupRepository.GetAsync(remark.Group.Id);

                remark.Group.Criteria = group.Value.Criteria;
                remark.Group.Members  = group.Value.Members.ToDictionary(x => x.UserId, x => x.Role);
            }
            await _cache.AddAsync(GetDetailsCacheKey(remark.Id), remark);

            if (addGeo)
            {
                await _cache.GeoAddAsync(GetGeoCacheKey(), remark.Location.Longitude, remark.Location.Latitude,
                                         remark.Id.ToString());
            }
            if (addLatest)
            {
                await _cache.AddToSortedSetAsync(GetLatestRemarksCacheKey(), remark.Id.ToString(), 0, limit : 100);
            }
        }
Esempio n. 13
0
        public async Task <T> GetAsync <T>(string cacheKey, TimeSpan cacheTimeout, bool cacheNullAndEmptyCollection,
                                           Func <Task <T> > delegateFunction) where T : class
        {
            var obj = await _cache.GetAsync(cacheKey);

            var foundInCache = obj != null;

            if (obj == null)
            {
                obj = await delegateFunction() ?? (object)(new CachedNullValue());

                if (IsCachable(obj, cacheNullAndEmptyCollection))
                {
                    await _cache.AddAsync(cacheKey, obj, DateTime.Now.Add(cacheTimeout));
                }
            }

            if (obj is CachedNullValue)
            {
                return(null);
            }

            return((T)obj);
        }
Esempio n. 14
0
 /// <summary>
 /// 使用<paramref name="pairs"/>作为缓存键值对,进行缓存添加
 /// 并以<paramref name="second"/>作为滑动缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="second"></param>
 /// <param name="pairs"></param>
 /// <returns></returns>
 public static Task <IEnumerable <bool> > AddAsync <TValue>(this ICache cache, long second, IDictionary <string, TValue> pairs)
 {
     return(cache.AddAsync(TimeSpan.FromSeconds(second), pairs));
 }
Esempio n. 15
0
 /// <summary>
 /// 添加
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="timeSpan">超时时间</param>
 /// <param name="cache">缓存实现</param>
 /// <returns></returns>
 public static bool Add <T>(this ICache cache, string key, T value, TimeSpan?timeSpan = default(TimeSpan?))
 {
     return(cache.AddAsync(key, value, timeSpan)
            .GetAwaiter()
            .GetResult());
 }
Esempio n. 16
0
 /// <summary>
 /// 批量添加
 /// </summary>
 /// <param name="kvs"></param>
 /// <param name="timeSpan"></param>
 /// <param name="cache">缓存实现</param>
 /// <returns></returns>
 public static bool Add <T>(this ICache cache, IDictionary <string, T> kvs, TimeSpan?timeSpan = default(TimeSpan?))
 {
     return(cache.AddAsync(kvs, timeSpan)
            .GetAwaiter()
            .GetResult());
 }
Esempio n. 17
0
 /// <summary>
 /// 添加<paramref name="key"/>的缓存<paramref name="value"/>
 /// 并使用<paramref name="second"/>作为滚动缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key"></param>
 /// <param name="second"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static Task <bool> AddAsync(this ICache cache, string key, long second, object value)
 {
     return(cache.AddAsync(key, value, TimeSpan.FromSeconds(second)));
 }
		public async Task<ResponseHandlerResult> HandleResponseAsync(HttpContextBase context, IResponse suggestedResponse, ICache cache, string cacheKey)
		{
			context.ThrowIfNull("context");
			suggestedResponse.ThrowIfNull("suggestedResponse");

			if (!suggestedResponse.CachePolicy.HasPolicy || cache == null || cacheKey == null)
			{
				return ResponseHandlerResult.ResponseNotHandled();
			}

			CacheItem cacheItem = await cache.GetAsync(cacheKey);
			string responseETag = suggestedResponse.CachePolicy.ETag;

			#region If-Match precondition header

			IfMatchHeader[] ifMatchHeaders = IfMatchHeader.ParseMany(context.Request.Headers["If-Match"]).ToArray();

			// Only consider If-Match headers if response status code is 2xx or 412
			if (ifMatchHeaders.Any() && ((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412))
			{
				// Return 412 if no If-Match header matches the response ETag
				// Return 412 if an "If-Match: *" header is present and the response has no ETag
				if (ifMatchHeaders.All(arg => arg.EntityTag.Value != responseETag) ||
				    (responseETag == null && ifMatchHeaders.Any(arg => arg.EntityTag.Value == "*")))
				{
					return await WriteResponseAsync(context.Response, new Response().PreconditionFailed());
				}
			}

			#endregion

			#region If-None-Match precondition header

			IfNoneMatchHeader[] ifNoneMatchHeaders = IfNoneMatchHeader.ParseMany(context.Request.Headers["If-None-Match"]).ToArray();

			if (ifNoneMatchHeaders.Any())
			{
				// Return 304 if an If-None-Match header matches the response ETag and the request method was GET or HEAD
				// Return 304 if an "If-None-Match: *" header is present, the response has an ETag and the request method was GET or HEAD
				// Return 412 if an "If-None-Match: *" header is present, the response has an ETag and the request method was not GET or HEAD
				if (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == responseETag) ||
				    (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == "*") && responseETag != null))
				{
					if (String.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) || String.Equals(context.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
					{
						if (cacheItem != null)
						{
							cacheItem.Response.CachePolicy.Apply(context.Response.Cache);
						}
						else
						{
							suggestedResponse.CachePolicy.Apply(context.Response.Cache);
						}

						return await WriteResponseAsync(context.Response, new Response().NotModified());
					}

					return await WriteResponseAsync(context.Response, new Response().PreconditionFailed());
				}
			}

			#endregion

			#region If-Modified-Since precondition header

			IfModifiedSinceHeader ifModifiedSinceHeader = IfModifiedSinceHeader.Parse(context.Request.Headers["If-Modified-Since"]);
			bool validIfModifiedSinceHttpDate = ifModifiedSinceHeader != null && ifModifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

			// Only consider an If-Modified-Since header if response status code is 200 and the HTTP-date is valid
			if (suggestedResponse.StatusCode.ParsedStatusCode == HttpStatusCode.OK && validIfModifiedSinceHttpDate)
			{
				// Return 304 if the response was cached before the HTTP-date
				if (cacheItem != null && cacheItem.CachedUtcTimestamp < ifModifiedSinceHeader.HttpDate)
				{
					return await WriteResponseAsync(context.Response, new Response().NotModified());
				}
			}

			#endregion

			#region If-Unmodified-Since precondition header

			IfUnmodifiedSinceHeader ifUnmodifiedSinceHeader = IfUnmodifiedSinceHeader.Parse(context.Request.Headers["If-Unmodified-Since"]);
			bool validIfUnmodifiedSinceHttpDate = ifUnmodifiedSinceHeader != null && ifUnmodifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

			// Only consider an If-Unmodified-Since header if response status code is 2xx or 412 and the HTTP-date is valid
			if (((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412) && validIfUnmodifiedSinceHttpDate)
			{
				// Return 412 if the previous response was removed from the cache or was cached again at a later time
				if (cacheItem == null || cacheItem.CachedUtcTimestamp >= ifUnmodifiedSinceHeader.HttpDate)
				{
					return await WriteResponseAsync(context.Response, new Response().PreconditionFailed());
				}
			}

			#endregion

			#region No server caching

			// Do not cache the response when the response sends a non-cacheable status code, or when an Authorization header is present
			if (!_cacheableStatusCodes.Contains(suggestedResponse.StatusCode) || context.Request.Headers["Authorization"] != null)
			{
				return await WriteResponseAsync(context.Response, suggestedResponse);
			}

			CacheControlHeader cacheControlHeader = CacheControlHeader.Parse(context.Request.Headers["Cache-Control"]);

			// Do not cache the response if a "Cache-Control: no-cache" or "Cache-Control: no-store" header is present
			if (cacheControlHeader != null && (cacheControlHeader.NoCache || cacheControlHeader.NoStore))
			{
				return await WriteResponseAsync(context.Response, suggestedResponse);
			}

			IEnumerable<PragmaHeader> pragmaHeader = PragmaHeader.ParseMany(context.Request.Headers["Pragma"]);

			// Do not cache the response if a "Pragma: no-cache" header is present
			if (pragmaHeader.Any(arg => String.Equals(arg.Name, "no-cache", StringComparison.OrdinalIgnoreCase)))
			{
				return await WriteResponseAsync(context.Response, suggestedResponse);
			}

			#endregion

			// Return 504 if the response has not been cached but the client is requesting to receive only a cached response
			if (cacheItem == null && cacheControlHeader != null && cacheControlHeader.OnlyIfCached)
			{
				return await WriteResponseAsync(context.Response, new Response().GatewayTimeout());
			}

			if (cacheItem != null)
			{
				// Write the cached response if no Cache-Control header is present
				// Write the cached response if a "Cache-Control: max-age" header is validated
				// Write the cached response if a "Cache-Control: max-stale" header is validated
				// Write the cached response if a "Cache-Control: min-fresh" header is validated
				if (cacheControlHeader == null ||
				    _systemClock.UtcDateTime - cacheItem.CachedUtcTimestamp <= cacheControlHeader.MaxAge ||
				    cacheControlHeader.OnlyIfCached ||
				    cacheItem.ExpiresUtcTimestamp == null ||
				    _systemClock.UtcDateTime - cacheItem.ExpiresUtcTimestamp.Value <= cacheControlHeader.MaxStale ||
				    cacheItem.ExpiresUtcTimestamp.Value - _systemClock.UtcDateTime < cacheControlHeader.MinFresh)
				{
					return await WriteResponseInCacheAsync(context.Response, cacheItem);
				}
			}

			bool cacheOnServer = suggestedResponse.CachePolicy.AllowsServerCaching;
			var cacheResponse = new CacheResponse(suggestedResponse);

			if (cacheOnServer)
			{
				DateTime expirationUtcTimestamp = suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp != null
					                                  ? suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp.Value
					                                  : _systemClock.UtcDateTime + suggestedResponse.CachePolicy.ServerCacheMaxAge.Value;

				await cache.AddAsync(cacheKey, cacheResponse, expirationUtcTimestamp);
			}

			return await WriteResponseAsync(context.Response, cacheResponse);
		}
 public async Task AddAsync(Group group)
 => await _cache.AddAsync(GetCacheKey(group.Id), group);
        public async Task <ResponseHandlerResult> HandleResponseAsync(HttpContextBase context, IResponse suggestedResponse, ICache cache, string cacheKey)
        {
            context.ThrowIfNull("context");
            suggestedResponse.ThrowIfNull("suggestedResponse");

            if (!suggestedResponse.CachePolicy.HasPolicy || cache == null || cacheKey == null)
            {
                return(ResponseHandlerResult.ResponseNotHandled());
            }

            CacheItem cacheItem = await cache.GetAsync(cacheKey);

            string responseETag = suggestedResponse.CachePolicy.ETag;

            #region If-Match precondition header

            IfMatchHeader[] ifMatchHeaders = IfMatchHeader.ParseMany(context.Request.Headers["If-Match"]).ToArray();

            // Only consider If-Match headers if response status code is 2xx or 412
            if (ifMatchHeaders.Any() && ((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412))
            {
                // Return 412 if no If-Match header matches the response ETag
                // Return 412 if an "If-Match: *" header is present and the response has no ETag
                if (ifMatchHeaders.All(arg => arg.EntityTag.Value != responseETag) ||
                    (responseETag == null && ifMatchHeaders.Any(arg => arg.EntityTag.Value == "*")))
                {
                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region If-None-Match precondition header

            IfNoneMatchHeader[] ifNoneMatchHeaders = IfNoneMatchHeader.ParseMany(context.Request.Headers["If-None-Match"]).ToArray();

            if (ifNoneMatchHeaders.Any())
            {
                // Return 304 if an If-None-Match header matches the response ETag and the request method was GET or HEAD
                // Return 304 if an "If-None-Match: *" header is present, the response has an ETag and the request method was GET or HEAD
                // Return 412 if an "If-None-Match: *" header is present, the response has an ETag and the request method was not GET or HEAD
                if (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == responseETag) ||
                    (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == "*") && responseETag != null))
                {
                    if (String.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) || String.Equals(context.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
                    {
                        if (cacheItem != null)
                        {
                            cacheItem.Response.CachePolicy.Apply(context.Response.Cache);
                        }
                        else
                        {
                            suggestedResponse.CachePolicy.Apply(context.Response.Cache);
                        }

                        return(await WriteResponseAsync(context.Response, new Response().NotModified()));
                    }

                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region If-Modified-Since precondition header

            IfModifiedSinceHeader ifModifiedSinceHeader = IfModifiedSinceHeader.Parse(context.Request.Headers["If-Modified-Since"]);
            bool validIfModifiedSinceHttpDate           = ifModifiedSinceHeader != null && ifModifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

            // Only consider an If-Modified-Since header if response status code is 200 and the HTTP-date is valid
            if (suggestedResponse.StatusCode.ParsedStatusCode == HttpStatusCode.OK && validIfModifiedSinceHttpDate)
            {
                // Return 304 if the response was cached before the HTTP-date
                if (cacheItem != null && cacheItem.CachedUtcTimestamp < ifModifiedSinceHeader.HttpDate)
                {
                    return(await WriteResponseAsync(context.Response, new Response().NotModified()));
                }
            }

            #endregion

            #region If-Unmodified-Since precondition header

            IfUnmodifiedSinceHeader ifUnmodifiedSinceHeader = IfUnmodifiedSinceHeader.Parse(context.Request.Headers["If-Unmodified-Since"]);
            bool validIfUnmodifiedSinceHttpDate             = ifUnmodifiedSinceHeader != null && ifUnmodifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

            // Only consider an If-Unmodified-Since header if response status code is 2xx or 412 and the HTTP-date is valid
            if (((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412) && validIfUnmodifiedSinceHttpDate)
            {
                // Return 412 if the previous response was removed from the cache or was cached again at a later time
                if (cacheItem == null || cacheItem.CachedUtcTimestamp >= ifUnmodifiedSinceHeader.HttpDate)
                {
                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region No server caching

            // Do not cache the response when the response sends a non-cacheable status code, or when an Authorization header is present
            if (!_cacheableStatusCodes.Contains(suggestedResponse.StatusCode) || context.Request.Headers["Authorization"] != null)
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            CacheControlHeader cacheControlHeader = CacheControlHeader.Parse(context.Request.Headers["Cache-Control"]);

            // Do not cache the response if a "Cache-Control: no-cache" or "Cache-Control: no-store" header is present
            if (cacheControlHeader != null && (cacheControlHeader.NoCache || cacheControlHeader.NoStore))
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            IEnumerable <PragmaHeader> pragmaHeader = PragmaHeader.ParseMany(context.Request.Headers["Pragma"]);

            // Do not cache the response if a "Pragma: no-cache" header is present
            if (pragmaHeader.Any(arg => String.Equals(arg.Name, "no-cache", StringComparison.OrdinalIgnoreCase)))
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            #endregion

            // Return 504 if the response has not been cached but the client is requesting to receive only a cached response
            if (cacheItem == null && cacheControlHeader != null && cacheControlHeader.OnlyIfCached)
            {
                return(await WriteResponseAsync(context.Response, new Response().GatewayTimeout()));
            }

            if (cacheItem != null)
            {
                // Write the cached response if no Cache-Control header is present
                // Write the cached response if a "Cache-Control: max-age" header is validated
                // Write the cached response if a "Cache-Control: max-stale" header is validated
                // Write the cached response if a "Cache-Control: min-fresh" header is validated
                if (cacheControlHeader == null ||
                    _systemClock.UtcDateTime - cacheItem.CachedUtcTimestamp <= cacheControlHeader.MaxAge ||
                    cacheControlHeader.OnlyIfCached ||
                    cacheItem.ExpiresUtcTimestamp == null ||
                    _systemClock.UtcDateTime - cacheItem.ExpiresUtcTimestamp.Value <= cacheControlHeader.MaxStale ||
                    cacheItem.ExpiresUtcTimestamp.Value - _systemClock.UtcDateTime < cacheControlHeader.MinFresh)
                {
                    return(await WriteResponseInCacheAsync(context.Response, cacheItem));
                }
            }

            bool cacheOnServer = suggestedResponse.CachePolicy.AllowsServerCaching;
            var  cacheResponse = new CacheResponse(suggestedResponse);

            if (cacheOnServer)
            {
                DateTime expirationUtcTimestamp = suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp != null
                                        ? suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp.Value
                                        : _systemClock.UtcDateTime + suggestedResponse.CachePolicy.ServerCacheMaxAge.Value;

                await cache.AddAsync(cacheKey, cacheResponse, expirationUtcTimestamp);
            }

            return(await WriteResponseAsync(context.Response, cacheResponse));
        }
Esempio n. 21
0
 /// <summary>
 /// 添加<paramref name="key"/>的缓存<paramref name="value"/>
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 public static Task <bool> AddAsync(this ICache cache, string key, object value)
 {
     return(cache.AddAsync(new CacheDescription(key, value)));
 }
Esempio n. 22
0
 /// <summary>
 /// 使用<paramref name="pairs"/>作为缓存键值对,进行缓存添加
 /// 并以<paramref name="second"/>作为滑动缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="second"></param>
 /// <param name="pairs"></param>
 /// <returns></returns>
 public static IEnumerable <bool> Add <TValue>(this ICache cache, long second, IDictionary <string, TValue> pairs)
 {
     return(cache.AddAsync(second, pairs)
            .GetAwaiter()
            .GetResult());
 }
Esempio n. 23
0
 public async Task Cache_null_key()
 {
     await cache.AddAsync(null, null, CacheInfo.DefaultExpiration);
 }
Esempio n. 24
0
 /// <summary>
 /// 保存刷新令牌
 /// </summary>
 /// <param name="token">刷新令牌</param>
 public async Task SaveRefreshTokenAsync(RefreshToken token) => await _cache.AddAsync(GetRefreshTokenKey(token.Value), token, token.EndUtcTime.Subtract(DateTime.UtcNow));
Esempio n. 25
0
 public async Task AddAsync(Operation operation)
 => await _cache.AddAsync(GetCacheKey(operation.RequestId),
                          operation, TimeSpan.FromMinutes(1));
Esempio n. 26
0
 /// <summary>
 /// 通过<paramref name="descriptions"/>批量添加缓存
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="descriptions"></param>
 /// <returns></returns>
 public static IEnumerable <bool> Add(this ICache cache, IEnumerable <CacheDescription> descriptions)
 {
     return(cache.AddAsync(descriptions).GetAwaiter().GetResult());
 }
Esempio n. 27
0
 public async Task AddAsync(UserNotificationSettings settings)
 => await _cache.AddAsync(GetCacheKey(settings.UserId), settings);
Esempio n. 28
0
 /// <summary>
 /// 异步添加一个缓存值
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">内容</param>
 /// <param name="expiry">时间</param>
 /// <returns></returns>
 public Task <bool> AddAsync(string key, object value, TimeSpan expiry)
 {
     return(_ICache.AddAsync(key, value, expiry));
 }
Esempio n. 29
0
 /// <summary>
 /// 使用<paramref name="pairs"/>作为缓存键值对,进行缓存添加
 /// 并以<paramref name="timeSpan"/>作为绝对缓存失效时间
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="pairs"></param>
 /// <param name="timeSpan"></param>
 /// <returns></returns>
 public static IEnumerable <bool> Add <TValue>(this ICache cache, IDictionary <string, TValue> pairs, TimeSpan timeSpan)
 {
     return(cache.AddAsync(pairs, timeSpan)
            .GetAwaiter()
            .GetResult());
 }
 public async Task AddAsync(Organization organization)
 => await _cache.AddAsync(GetCacheKey(organization.Id), organization);
Esempio n. 31
0
 /// <summary>
 /// 根据<paramref name="description"/>添加缓存
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="description"></param>
 /// <returns></returns>
 public static bool Add(this ICache cache, CacheDescription description)
 {
     return(cache.AddAsync(description)
            .GetAwaiter()
            .GetResult());
 }