Esempio n. 1
0
 /// <summary>
 /// Attempts to apply some caching rules to a response
 /// </summary>
 protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     var response = await base.SendAsync(request, cancellationToken);
     var cacheHeaders = new CacheControlHeaderValue
                        {
                            NoCache = true
                        };
     if ((int)response.StatusCode > 400 || // 400 and above are errors
         response.StatusCode == HttpStatusCode.NoContent || // no content, no cache
         response.StatusCode == HttpStatusCode.Created) // any 201 Created response is not cacheable as the response is based off of the request body
     {
         // no caching allowed
         cacheHeaders.NoStore = true;
     }
     else if (response.StatusCode == HttpStatusCode.OK)
     {
         // 200 Okay responses should generally be cached
         cacheHeaders.NoStore = false;
         cacheHeaders.Private = false;
         // always revalidate
         cacheHeaders.MaxAge = new TimeSpan(0, 0, 0);
     }
     response.Headers.CacheControl = cacheHeaders;
     return response;
 }
        public bool Should_be_determined_from_MaxAge_and_cacheControl(int maxAge, bool? noCache, bool? noStore, int? cacheControlMaxAge, bool ignoreRevalidation)
        {
            CacheControlHeaderValue cacheControl = null;
            if (noCache.HasValue || noStore.HasValue || cacheControlMaxAge.HasValue)
            {
                cacheControl = new CacheControlHeaderValue
                {
                    NoCache = noCache ?? false,
                    NoStore = noStore ?? false,
                };

                if (cacheControlMaxAge.HasValue)
                {
                    cacheControl.MaxAge = TimeSpan.FromSeconds(cacheControlMaxAge.Value);
                }
            }
            var att = new OutputCacheAttributeWithPublicMethods
            {
                MaxAge = (uint)maxAge,
                IgnoreRevalidationRequest = ignoreRevalidation
            };

            // Action
            return att.ShouldIgnoreCachePublic(cacheControl, new HttpRequestMessage());
        }
Esempio n. 3
0
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     var cachecontrol = new CacheControlHeaderValue();
     cachecontrol.MaxAge = TimeSpan.FromSeconds(_clientTimeSpan);
     cachecontrol.MustRevalidate = true;
     actionExecutedContext.ActionContext.Response.Headers.CacheControl = cachecontrol;
 }
        public void Should_return_null_if_cache_not_mature_as_min_fresh_request()
        {
            // Arrange
            var cacheControl = new CacheControlHeaderValue
            {
                MinFresh = TimeSpan.FromSeconds(100)
            };

            var cacheItem = new WebApiCacheItem
            {
                CreatedTime = DateTime.UtcNow.AddSeconds(-20),
                MaxAge = 1000,
                StaleWhileRevalidate = 5,
                IgnoreRevalidationRequest = false
            };

            var request = new HttpRequestMessage();
            var svc = new CacheResponseBuilder { };

            // Action
            var response = svc.GetResponse(cacheControl, cacheItem, request);

            // Assert
            Assert.IsNull(response);
        }
 public void Subscribe(Uri subscriptionUri, Uri callbackUri, TimeSpan subscriptionTimeSpan)
 {
     var httpClient = new HttpClient();
     var req = new HttpRequestMessage
     {
         RequestUri = subscriptionUri,
         Version = HttpVersion.Version11
     };
     req.Headers.UserAgent.Add(new ProductInfoHeaderValue("SimpleSonos", "1.0"));
     req.Method = new HttpMethod("SUBSCRIBE");
     req.Headers.Add("CALLBACK", "<" + callbackUri.AbsoluteUri + ">");
     req.Headers.Add("NT", "upnp:event");
     req.Headers.Add("TIMEOUT", "Second-" + (int) subscriptionTimeSpan.TotalSeconds);
     req.Headers.ConnectionClose = true;
     var cch = new CacheControlHeaderValue {NoCache = true};
     req.Headers.CacheControl = cch;
     try
     {
         var resp = httpClient.SendAsync(req).Result;
         Console.WriteLine("Gor response from " + subscriptionUri.Host + ". StatusCode: " + resp.StatusCode);
         if (resp.Headers.Contains("SID"))
             Console.WriteLine("SID: " + resp.Headers.GetValues("SID").First());
         if (resp.Headers.Contains("TIMEOUT"))
             Console.WriteLine("TIMEOUT: " + resp.Headers.GetValues("TIMEOUT").First());
         if (resp.Headers.Contains("Server"))
             Console.WriteLine("Server: " + resp.Headers.GetValues("Server").First());
     }
     catch (Exception e)
     {
         Console.WriteLine("ERROR TRYING TO SUBSCRIBE " + e);
     }
 }
 private CacheControlHeaderValue setClientCache()
 {
     var cachecontrol = new CacheControlHeaderValue();
     cachecontrol.MaxAge = TimeSpan.FromSeconds(_clientTimeSpan);
     cachecontrol.MustRevalidate = true;
     return cachecontrol;
 }
Esempio n. 7
0
		public NotModifiedResponse(HttpRequestMessage request, CacheControlHeaderValue cacheControlHeaderValue, EntityTagHeaderValue etag)
			: base(HttpStatusCode.NotModified)
		{
			if(etag!=null)
				this.Headers.ETag = etag;
		    this.Headers.CacheControl = cacheControlHeaderValue;
			this.RequestMessage = request;
		}
 private void CheckValidParsedValue(string input, int startIndex, CacheControlHeaderValue expectedResult,
     int expectedIndex)
 {
     HttpHeaderParser parser = CacheControlHeaderParser.Parser;
     object result = null;
     Assert.True(parser.TryParseValue(input, null, ref startIndex, out result));
     Assert.Equal(expectedIndex, startIndex);
     Assert.Equal(result, expectedResult);
 }
 /// <summary>
 /// default .ctor is no cache policy
 /// </summary>
 public HttpCacheControlPolicyAttribute()
 {
     _cacheControl = new CacheControlHeaderValue()
                         {
                             Private = true,
                             NoCache = true,
                             NoStore = true
                         };
 }
Esempio n. 10
0
 private CacheControlHeaderValue SetClientCache()
 {
     var cachecontrol = new CacheControlHeaderValue
     {
         MaxAge = TimeSpan.FromSeconds(Duration),
         MustRevalidate = true
     };
     return cachecontrol;
 }
        public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter()
        {
            CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();

            // Bool properties
            cacheControl.NoCache = true;
            Assert.True(cacheControl.NoCache);
            cacheControl.NoStore = true;
            Assert.True(cacheControl.NoStore);
            cacheControl.MaxStale = true;
            Assert.True(cacheControl.MaxStale);
            cacheControl.NoTransform = true;
            Assert.True(cacheControl.NoTransform);
            cacheControl.OnlyIfCached = true;
            Assert.True(cacheControl.OnlyIfCached);
            cacheControl.Public = true;
            Assert.True(cacheControl.Public);
            cacheControl.Private = true;
            Assert.True(cacheControl.Private);
            cacheControl.MustRevalidate = true;
            Assert.True(cacheControl.MustRevalidate);
            cacheControl.ProxyRevalidate = true;
            Assert.True(cacheControl.ProxyRevalidate);

            // TimeSpan properties
            TimeSpan timeSpan = new TimeSpan(1, 2, 3);
            cacheControl.MaxAge = timeSpan;
            Assert.Equal(timeSpan, cacheControl.MaxAge);
            cacheControl.SharedMaxAge = timeSpan;
            Assert.Equal(timeSpan, cacheControl.SharedMaxAge);
            cacheControl.MaxStaleLimit = timeSpan;
            Assert.Equal(timeSpan, cacheControl.MaxStaleLimit);
            cacheControl.MinFresh = timeSpan;
            Assert.Equal(timeSpan, cacheControl.MinFresh);

            // String collection properties
            Assert.NotNull(cacheControl.NoCacheHeaders);
            Assert.Throws<ArgumentException>(() => { cacheControl.NoCacheHeaders.Add(null); });
            Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); });
            cacheControl.NoCacheHeaders.Add("token");
            Assert.Equal(1, cacheControl.NoCacheHeaders.Count);
            Assert.Equal("token", cacheControl.NoCacheHeaders.First());

            Assert.NotNull(cacheControl.PrivateHeaders);
            Assert.Throws<ArgumentException>(() => { cacheControl.PrivateHeaders.Add(null); });
            Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); });
            cacheControl.PrivateHeaders.Add("token");
            Assert.Equal(1, cacheControl.PrivateHeaders.Count);
            Assert.Equal("token", cacheControl.PrivateHeaders.First());

            // NameValueHeaderValue collection property
            Assert.NotNull(cacheControl.Extensions);
            Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); });
            cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value"));
            Assert.Equal(1, cacheControl.Extensions.Count);
            Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First());
        }
        /// <summary>
        /// Sets the cache headers
        /// </summary>
        /// <param name="response">The actual response</param>
        protected virtual void ApplyCacheHeaders(
            HttpResponseMessage response)
        {
            var cacheControl = new CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromSeconds(ClientTimeSpan)
            };

            response.Headers.CacheControl = cacheControl;
        }
 public HttpCacheControlPolicyAttribute(bool isPrivate, int maxAgeInSeconds)
     : this()
 {
     _cacheControl = new CacheControlHeaderValue()
     {
         Private = isPrivate,
         Public = !isPrivate,
         MustRevalidate = true,
         MaxAge = TimeSpan.FromSeconds(maxAgeInSeconds)
     };
 }
        /// <summary>
        /// Uses a factory type to provide the value.
        /// This type can read from config, etc.
        /// Must have a public parameterless method that return CacheControlHeaderValue
        /// </summary>
        /// <param name="cacheControlHeaderValueFactory">The type of the factory. 
        /// Any public method that returns CacheControlHeaderValue will be used.
        /// Type's constructor must be parameterless</param>
        public HttpCacheControlPolicyAttribute(Type cacheControlHeaderValueFactory)
        {
            var factory = Activator.CreateInstance(cacheControlHeaderValueFactory);
            var method = factory.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
                .FirstOrDefault(m => m.ReturnType == typeof(CacheControlHeaderValue));

            if(method == null)
                throw new ArgumentException("This type does not have a factory method: " + cacheControlHeaderValueFactory.FullName);

            _cacheControl = (CacheControlHeaderValue) method.Invoke(factory, new object[0]);
        }
        public void Should_return_GatewayTimeout_when_no_cache_and_request_sent_OnlyIfCached_control()
        {
            // Arrange
            var cacheControl = new CacheControlHeaderValue {OnlyIfCached  = true};
            var svc = new CacheResponseBuilder();

            // Action
            var result = svc.GetResponse(cacheControl, null, new HttpRequestMessage());

            // Assert
            Assert.AreEqual(HttpStatusCode.GatewayTimeout, result.StatusCode);
            Assert.AreEqual("no cache available", result.Headers.GetValues("X-Flatwhite-Message").Single());
        }
        public void HttpProvider_CustomCacheHeaderAndTimeout()
        {
            var timeout = TimeSpan.FromSeconds(200);
            var cacheHeader = new CacheControlHeaderValue();
            using (var defaultHttpProvider = new HttpProvider(null) { CacheControlHeader = cacheHeader, OverallTimeout = timeout })
            {
                Assert.IsFalse(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoCache, "NoCache true.");
                Assert.IsFalse(defaultHttpProvider.httpClient.DefaultRequestHeaders.CacheControl.NoStore, "NoStore true.");

                Assert.AreEqual(timeout, defaultHttpProvider.httpClient.Timeout, "Unexpected default timeout set.");
                Assert.IsNotNull(defaultHttpProvider.Serializer, "Serializer not initialized.");
                Assert.IsInstanceOfType(defaultHttpProvider.Serializer, typeof(Serializer), "Unexpected serializer initialized.");
            }
        }
        public async Task Should_return_new_etag_if_cache_item_found_but_doesnt_match_checksum(string cacheChecksum, HttpStatusCode resultCode)
        {
            // Arrange
            
            var cacheControl = new CacheControlHeaderValue
            {
                MaxStale = true,
                MaxStaleLimit = TimeSpan.FromSeconds(15),
                MinFresh = TimeSpan.FromSeconds(20)
            };

            var oldCacheItem = new WebApiCacheItem
            {
                CreatedTime = DateTime.UtcNow.AddSeconds(-11),
                MaxAge = 10,
                StaleWhileRevalidate = 5,
                IgnoreRevalidationRequest = true,
                ResponseCharSet = "UTF8",
                ResponseMediaType = "text/json",
                Content = new byte[0],
                Key = "fw-0-HASHEDKEY",
                Checksum = cacheChecksum
            };

            var request = new HttpRequestMessage
            {
                Method = new HttpMethod("GET"),
                RequestUri = new Uri("http://localhost")
            };

            request.Headers.Add("If-None-Match", "\"fw-0-HASHEDKEY-OLDCHECKSUM\"");
            var builder = new CacheResponseBuilder();
            var handler = new EtagHeaderHandler(builder);
            await Global.CacheStoreProvider.GetAsyncCacheStore().SetAsync("fw-0-HASHEDKEY", oldCacheItem, DateTimeOffset.Now.AddDays(1)).ConfigureAwait(false);


            // Action
            Global.Cache.PhoenixFireCage["fw-0-HASHEDKEY"] = new WebApiPhoenix(NSubstitute.Substitute.For<_IInvocation>(), new CacheInfo(), oldCacheItem, request);
            var response = await handler.HandleAsync(cacheControl, request, CancellationToken.None).ConfigureAwait(false);

            Assert.AreEqual(resultCode, response.StatusCode);
            if (resultCode == HttpStatusCode.OK)
            {
                Assert.AreEqual($"\"fw-0-HASHEDKEY-{cacheChecksum}\"", response.Headers.ETag.Tag);
            }
            else
            {
                Assert.IsNull(response.Headers.ETag);
            }
        }
        public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
        {
            // Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
            CacheControlHeaderValue expected = new CacheControlHeaderValue();
            expected.NoStore = true;
            expected.MinFresh = new TimeSpan(0, 2, 3);
            CheckValidParsedValue("X , , no-store, min-fresh=123", 1, expected, 29);

            expected = new CacheControlHeaderValue();
            expected.MaxStale = true;
            expected.NoCache = true;
            expected.NoCacheHeaders.Add("t");
            CheckValidParsedValue("max-stale, no-cache=\"t\", ,,", 0, expected, 27);
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Response.StatusCode >= HttpStatusCode.InternalServerError)
            {
                return;
            }

            var cachecontrol = new CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromSeconds(ClientTimeSpan),
                MustRevalidate = true,
                Public = true
            };

            actionExecutedContext.Response.Headers.CacheControl = cachecontrol;
        }
        public async Task Should_return_null_if_no_etag_in_request()
        {
            // Arrange
            var cacheControl = new CacheControlHeaderValue();
            var request = new HttpRequestMessage
            {
                Method = new HttpMethod("GET"),
                RequestUri = new Uri("http://localhost")
            };
            var builder = Substitute.For<ICacheResponseBuilder>();
            var handler = new EtagHeaderHandler(builder);
            
            // Action
            var response = await handler.HandleAsync(cacheControl, request, CancellationToken.None);

            Assert.IsNull(response);
        }
        public void TestRefreshPolicyFor404()
        {
            var configuration = new HttpConfiguration(new HttpRouteCollection("/"));
            configuration.Services.Replace(typeof (IHttpControllerSelector), new NotFoundControllerSelector());
            configuration.Routes.MapHttpRoute("main", "api/{controller}/{id}");
            var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://aliostad/api/CachePolicyAction/1"));
            var routeData = configuration.Routes.GetRouteData(request);
            request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, (object)routeData);
            var headerValue = new CacheControlHeaderValue();
            var attributeBasedCachePolicy = new AttributeBasedCacheControlPolicy(headerValue);

            // act
            var cchv = attributeBasedCachePolicy.GetCacheControl(request, configuration);

            // assert
            Assert.AreEqual(headerValue, cchv);

        }
        public async Task Should_return_null_if_cache_item_not_found()
        {
            // Arrange
            var cacheControl = new CacheControlHeaderValue();
            var request = new HttpRequestMessage
            {
                Method = new HttpMethod("GET"),
                RequestUri = new Uri("http://localhost")
            };
            request.Headers.Add("If-None-Match", "\"fw-1000-HASHEDKEY-CHECKSUM\"");
            var builder = Substitute.For<ICacheResponseBuilder>();
            var handler = new EtagHeaderHandler(builder);

            // Action
            var response = await handler.HandleAsync(cacheControl, request, CancellationToken.None);

            Assert.IsNull(response);
        }
 public HttpCacheControlPolicyAttribute(bool isPrivate, 
     int maxAgeInSeconds,
     bool mustRevalidate = true,
     bool noCache = false,
     bool noTransform = false)
     : this()
 {
     // copy values to the header
     _cacheControl = new CacheControlHeaderValue()
     {
         Private = isPrivate,
         Public = !isPrivate,
         MustRevalidate = mustRevalidate,
         MaxAge = TimeSpan.FromSeconds(maxAgeInSeconds),
         NoCache = noCache,
         NoTransform = noTransform
     };
 }
Esempio n. 24
0
 protected CacheControlHeaderValue CloneCacheControlHeaderValue(CacheControlHeaderValue headerValue)
 {
     return new CacheControlHeaderValue()
                {
                    MaxAge = headerValue.MaxAge,
                    MaxStale = headerValue.MaxStale,
                    MaxStaleLimit = headerValue.MaxStaleLimit,
                    MinFresh = headerValue.MinFresh,
                    MustRevalidate = headerValue.MustRevalidate,
                    NoCache = headerValue.NoCache,
                    NoStore = headerValue.NoStore,
                    NoTransform = headerValue.NoTransform,
                    OnlyIfCached = headerValue.OnlyIfCached,
                    Private = headerValue.Private,
                    ProxyRevalidate = headerValue.ProxyRevalidate,
                    Public = headerValue.Public,
                    SharedMaxAge = headerValue.SharedMaxAge
                };
 }
        private CacheControlHeaderValue(CacheControlHeaderValue source)
        {
            Debug.Assert(source != null);

            _noCache         = source._noCache;
            _noStore         = source._noStore;
            _maxAge          = source._maxAge;
            _sharedMaxAge    = source._sharedMaxAge;
            _maxStale        = source._maxStale;
            _maxStaleLimit   = source._maxStaleLimit;
            _minFresh        = source._minFresh;
            _noTransform     = source._noTransform;
            _onlyIfCached    = source._onlyIfCached;
            _publicField     = source._publicField;
            _privateField    = source._privateField;
            _mustRevalidate  = source._mustRevalidate;
            _proxyRevalidate = source._proxyRevalidate;

            if (source._noCacheHeaders != null)
            {
                foreach (var noCacheHeader in source._noCacheHeaders)
                {
                    NoCacheHeaders.Add(noCacheHeader);
                }
            }

            if (source._privateHeaders != null)
            {
                foreach (var privateHeader in source._privateHeaders)
                {
                    PrivateHeaders.Add(privateHeader);
                }
            }

            if (source._extensions != null)
            {
                foreach (var extension in source._extensions)
                {
                    Extensions.Add((NameValueHeaderValue)((ICloneable)extension).Clone());
                }
            }
        }
Esempio n. 26
0
        private CacheControlHeaderValue(CacheControlHeaderValue source)
        {
            Contract.Requires(source != null);

            noCache         = source.noCache;
            noStore         = source.noStore;
            maxAge          = source.maxAge;
            sharedMaxAge    = source.sharedMaxAge;
            maxStale        = source.maxStale;
            maxStaleLimit   = source.maxStaleLimit;
            minFresh        = source.minFresh;
            noTransform     = source.noTransform;
            onlyIfCached    = source.onlyIfCached;
            publicField     = source.publicField;
            privateField    = source.privateField;
            mustRevalidate  = source.mustRevalidate;
            proxyRevalidate = source.proxyRevalidate;

            if (source.noCacheHeaders != null)
            {
                foreach (var noCacheHeader in source.noCacheHeaders)
                {
                    NoCacheHeaders.Add(noCacheHeader);
                }
            }

            if (source.privateHeaders != null)
            {
                foreach (var privateHeader in source.privateHeaders)
                {
                    PrivateHeaders.Add(privateHeader);
                }
            }

            if (source.extensions != null)
            {
                foreach (var extension in source.extensions)
                {
                    Extensions.Add((NameValueHeaderValue)((ICloneable)extension).Clone());
                }
            }
        }
Esempio n. 27
0
        private CacheControlHeaderValue(CacheControlHeaderValue source)
        {
            Contract.Requires(source != null);

            noCache = source.noCache;
            noStore = source.noStore;
            maxAge = source.maxAge;
            sharedMaxAge = source.sharedMaxAge;
            maxStale = source.maxStale;
            maxStaleLimit = source.maxStaleLimit;
            minFresh = source.minFresh;
            noTransform = source.noTransform;
            onlyIfCached = source.onlyIfCached;
            publicField = source.publicField;
            privateField = source.privateField;
            mustRevalidate = source.mustRevalidate;
            proxyRevalidate = source.proxyRevalidate;

            if (source.noCacheHeaders != null)
            {
                foreach (var noCacheHeader in source.noCacheHeaders)
                {
                    NoCacheHeaders.Add(noCacheHeader);
                }
            }

            if (source.privateHeaders != null)
            {
                foreach (var privateHeader in source.privateHeaders)
                {
                    PrivateHeaders.Add(privateHeader);
                }
            }

            if (source.extensions != null)
            {
                foreach (var extension in source.extensions)
                {
                    Extensions.Add((NameValueHeaderValue)((ICloneable)extension).Clone());
                }
            }
        }
		public void Ctor_Default ()
		{
			var value = new CacheControlHeaderValue ();

			Assert.AreEqual (0, value.Extensions.Count, "#1");
			Assert.IsNull (value.MaxAge, "#2");
			Assert.IsFalse (value.MaxStale, "#3");
			Assert.IsNull (value.MaxStaleLimit, "#4");
			Assert.IsNull (value.MinFresh, "#5");
			Assert.IsFalse (value.MustRevalidate, "#6");
			Assert.IsFalse (value.NoCache, "#7");
			Assert.IsFalse (value.NoStore, "#8");
			Assert.IsFalse (value.NoTransform, "#9");
			Assert.IsFalse (value.OnlyIfCached, "#10");
			Assert.IsFalse (value.Private, "#11");
			Assert.AreEqual (0, value.PrivateHeaders.Count, "#12");
			Assert.IsFalse (value.ProxyRevalidate, "#13");
			Assert.IsFalse (value.Public, "#14");
			Assert.IsNull (value.SharedMaxAge, "#15");
		}
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            // if some exception happened before in pipeline, response will be null
            if (actionExecutedContext.Response == null)
            {
                return;
            }

            HttpStatusCode statusCode = actionExecutedContext.Response.StatusCode;
            if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NotModified)
            {
                var response = actionExecutedContext.Response;

                var cacheControl = new CacheControlHeaderValue();
                cacheControl.MaxAge = TimeSpan.FromSeconds(MaxAge);

                response.Headers.CacheControl = cacheControl;
            }

            base.OnActionExecuted(actionExecutedContext);
        }
Esempio n. 30
0
        public static void ApplyCacheRequestDirective(this HttpRequestMessage requestMessage, CacheRequestDirective cacheDirective, ConditionalRequestDirective conditionalDirective)
        {
            var cacheControlHeader = new CacheControlHeaderValue();
            cacheControlHeader.MaxAge = cacheDirective.MaxAge;
            cacheControlHeader.MaxStale = cacheDirective.MaxStale.HasValue;
            if (cacheDirective.MaxStale != TimeSpan.MaxValue)
                cacheControlHeader.MaxStaleLimit = cacheDirective.MaxStale;
            cacheControlHeader.MinFresh = cacheDirective.MinFresh;
            cacheControlHeader.NoCache = cacheDirective.NoCache;
            if (cacheDirective.NoCache)
                requestMessage.Headers.Pragma.Add(new NameValueHeaderValue("no-cache"));
            cacheControlHeader.NoStore = cacheDirective.NoStore;
            // TODO deal with no-transform
            cacheControlHeader.OnlyIfCached = cacheDirective.OnlyIfCached;
            requestMessage.Headers.CacheControl = cacheControlHeader;

            requestMessage.Headers.IfModifiedSince = conditionalDirective.IfModifiedSince;
            requestMessage.Headers.IfUnmodifiedSince = conditionalDirective.IfUnmodifiedSince;
            CopyETags(conditionalDirective.IfMatch, requestMessage.Headers.IfMatch);
            CopyETags(conditionalDirective.IfNoneMatch, requestMessage.Headers.IfNoneMatch);
        }
Esempio n. 31
0
        /// <summary>
        /// cacheControl ヘッダ値によりキャッシュ要素を作成、登録します。
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="cacheControl"></param>
        /// <param name="eTag"></param>
        /// <param name="content"></param>
        public static void CreateEntry(string requestUri,
            CacheControlHeaderValue cacheControl,
            string eTag,
            string content)
        {
            Contract.Requires(requestUri!=null);
            Contract.Requires(cacheControl!=null);
            Contract.Requires(eTag!=null);
            Contract.Requires(content!=null);

            if(CacheProvider==null) return;

            if( cacheControl.NoCache ) return;
            CacheProvider.CreateEntry(
                new CacheEntry(requestUri)
                    {
                        Content = content,
                        ETag = eTag,
                        ExpireAt = DateTime.UtcNow.Add(cacheControl.MaxAge ?? TimeSpan.FromSeconds(60))
                    });
        }
        /// <summary>
        /// Try to get the cache from etag and build the response if cache is available
        /// </summary>
        /// <param name="cacheControl"></param>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> HandleAsync(CacheControlHeaderValue cacheControl, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.IfNoneMatch != null)
            {
                // Etag format: fw-StoreId-HashedKey-Checksum
                var requestEtags = request.Headers.IfNoneMatch.Where(t => t.Tag != null && t.Tag.StartsWith("\"fw-")).ToList();
                if (requestEtags.Count > 0)
                {
                    foreach (var etag in requestEtags)
                    {
                        var etagString = etag.Tag.Trim('"');
                        var index = etagString.IndexOf("-", 4, StringComparison.Ordinal);
                        var storeIdString = index > 0 ? etagString.Substring(3, index - 3) : "0";
                        index = etagString.LastIndexOf("-", StringComparison.Ordinal);

                        int storeId;
                        IAsyncCacheStore cacheStore = null;
                        if (int.TryParse(storeIdString, out storeId))
                        {
                            cacheStore = Global.CacheStoreProvider.GetAsyncCacheStore(storeId) ?? Global.CacheStoreProvider.GetAsyncCacheStore();
                        }

                        if (cacheStore != null && index > 0)
                        {
                            var hashedKey = etagString.Substring(0, index);
                            var checkSum = etagString.Substring(index + 1);
                            var cacheItem = (await cacheStore.GetAsync(hashedKey)) as WebApiCacheItem;

                            if (cacheItem != null && cacheItem.Checksum == checkSum)
                            {
                                request.Properties[WebApiExtensions.__webApi_etag_matched] = true;
                            }
                            return _builder.GetResponse(cacheControl, cacheItem, request);
                        }
                    }
                }
            }
            return null;
        }
Esempio n. 33
0
        public override bool Equals(object obj)
        {
            CacheControlHeaderValue other = obj as CacheControlHeaderValue;

            if (other == null)
            {
                return(false);
            }

            if ((noCache != other.noCache) || (noStore != other.noStore) || (maxAge != other.maxAge) ||
                (sharedMaxAge != other.sharedMaxAge) || (maxStale != other.maxStale) ||
                (maxStaleLimit != other.maxStaleLimit) || (minFresh != other.minFresh) ||
                (noTransform != other.noTransform) || (onlyIfCached != other.onlyIfCached) ||
                (publicField != other.publicField) || (privateField != other.privateField) ||
                (mustRevalidate != other.mustRevalidate) || (proxyRevalidate != other.proxyRevalidate))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(noCacheHeaders, other.noCacheHeaders,
                                                     HeaderUtilities.CaseInsensitiveStringComparer))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(privateHeaders, other.privateHeaders,
                                                     HeaderUtilities.CaseInsensitiveStringComparer))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(extensions, other.extensions))
            {
                return(false);
            }

            return(true);
        }
        public override bool Equals(object obj)
        {
            CacheControlHeaderValue other = obj as CacheControlHeaderValue;

            if (other == null)
            {
                return(false);
            }

            if ((_noCache != other._noCache) || (_noStore != other._noStore) || (_maxAge != other._maxAge) ||
                (_sharedMaxAge != other._sharedMaxAge) || (_maxStale != other._maxStale) ||
                (_maxStaleLimit != other._maxStaleLimit) || (_minFresh != other._minFresh) ||
                (_noTransform != other._noTransform) || (_onlyIfCached != other._onlyIfCached) ||
                (_publicField != other._publicField) || (_privateField != other._privateField) ||
                (_mustRevalidate != other._mustRevalidate) || (_proxyRevalidate != other._proxyRevalidate))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(_noCacheHeaders, other._noCacheHeaders,
                                                     StringComparer.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(_privateHeaders, other._privateHeaders,
                                                     StringComparer.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (!HeaderUtilities.AreEqualCollections(_extensions, other._extensions))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 35
0
 public static bool TryParse(string input, out CacheControlHeaderValue parsedValue)
 {
     throw new NotImplementedException();
 }
Esempio n. 36
0
        public static bool TryParse(string input, out CacheControlHeaderValue parsedValue)
        {
            parsedValue = null;
            if (input == null)
            {
                return(true);
            }

            var value = new CacheControlHeaderValue();

            var   lexer = new Lexer(input);
            Token t;

            do
            {
                t = lexer.Scan();
                if (t != Token.Type.Token)
                {
                    return(false);
                }

                string   s          = lexer.GetStringValue(t);
                bool     token_read = false;
                TimeSpan?ts;
                switch (s)
                {
                case "no-store":
                    value.NoStore = true;
                    break;

                case "no-transform":
                    value.NoTransform = true;
                    break;

                case "only-if-cached":
                    value.OnlyIfCached = true;
                    break;

                case "public":
                    value.Public = true;
                    break;

                case "must-revalidate":
                    value.MustRevalidate = true;
                    break;

                case "proxy-revalidate":
                    value.ProxyRevalidate = true;
                    break;

                case "max-stale":
                    value.MaxStale = true;
                    t = lexer.Scan();
                    if (t != Token.Type.SeparatorEqual)
                    {
                        token_read = true;
                        break;
                    }

                    t = lexer.Scan();
                    if (t != Token.Type.Token)
                    {
                        return(false);
                    }

                    ts = lexer.TryGetTimeSpanValue(t);
                    if (ts == null)
                    {
                        return(false);
                    }

                    value.MaxStaleLimit = ts;
                    break;

                case "max-age":
                case "s-maxage":
                case "min-fresh":
                    t = lexer.Scan();
                    if (t != Token.Type.SeparatorEqual)
                    {
                        return(false);
                    }

                    t = lexer.Scan();
                    if (t != Token.Type.Token)
                    {
                        return(false);
                    }

                    ts = lexer.TryGetTimeSpanValue(t);
                    if (ts == null)
                    {
                        return(false);
                    }

                    switch (s.Length)
                    {
                    case 7:
                        value.MaxAge = ts;
                        break;

                    case 8:
                        value.SharedMaxAge = ts;
                        break;

                    default:
                        value.MinFresh = ts;
                        break;
                    }

                    break;

                case "private":
                case "no-cache":
                    if (s.Length == 7)
                    {
                        value.Private = true;
                    }
                    else
                    {
                        value.NoCache = true;
                    }

                    t = lexer.Scan();
                    if (t != Token.Type.SeparatorEqual)
                    {
                        token_read = true;
                        break;
                    }

                    t = lexer.Scan();
                    if (t != Token.Type.QuotedString)
                    {
                        return(false);
                    }

                    foreach (var entry in lexer.GetQuotedStringValue(t).Split(','))
                    {
                        var qs = entry.Trim('\t', ' ');

                        if (s.Length == 7)
                        {
                            value.PrivateHeaders.Add(qs);
                        }
                        else
                        {
                            value.NoCache = true;
                            value.NoCacheHeaders.Add(qs);
                        }
                    }
                    break;

                default:
                    string name   = lexer.GetStringValue(t);
                    string svalue = null;

                    t = lexer.Scan();
                    if (t == Token.Type.SeparatorEqual)
                    {
                        t = lexer.Scan();
                        switch (t.Kind)
                        {
                        case Token.Type.Token:
                        case Token.Type.QuotedString:
                            svalue = lexer.GetStringValue(t);
                            break;

                        default:
                            return(false);
                        }
                    }
                    else
                    {
                        token_read = true;
                    }

                    value.Extensions.Add(NameValueHeaderValue.Create(name, svalue));
                    break;
                }

                if (!token_read)
                {
                    t = lexer.Scan();
                }
            } while (t == Token.Type.SeparatorComma);

            if (t != Token.Type.End)
            {
                return(false);
            }

            parsedValue = value;
            return(true);
        }
Esempio n. 37
0
 public static bool TryParse(string input, out CacheControlHeaderValue parsedValue)
 {
 }
        private static bool TrySetCacheControlValues(CacheControlHeaderValue cc,
                                                     List <NameValueHeaderValue> nameValueList)
        {
            foreach (NameValueHeaderValue nameValue in nameValueList)
            {
                bool   success = true;
                string name    = nameValue.Name.ToLowerInvariant();

                switch (name)
                {
                case noCacheString:
                    success = TrySetOptionalTokenList(nameValue, ref cc._noCache, ref cc._noCacheHeaders);
                    break;

                case noStoreString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._noStore);
                    break;

                case maxAgeString:
                    success = TrySetTimeSpan(nameValue, ref cc._maxAge);
                    break;

                case maxStaleString:
                    success = ((nameValue.Value == null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit));
                    if (success)
                    {
                        cc._maxStale = true;
                    }
                    break;

                case minFreshString:
                    success = TrySetTimeSpan(nameValue, ref cc._minFresh);
                    break;

                case noTransformString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._noTransform);
                    break;

                case onlyIfCachedString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._onlyIfCached);
                    break;

                case publicString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._publicField);
                    break;

                case privateString:
                    success = TrySetOptionalTokenList(nameValue, ref cc._privateField, ref cc._privateHeaders);
                    break;

                case mustRevalidateString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._mustRevalidate);
                    break;

                case proxyRevalidateString:
                    success = TrySetTokenOnlyValue(nameValue, ref cc._proxyRevalidate);
                    break;

                case sharedMaxAgeString:
                    success = TrySetTimeSpan(nameValue, ref cc._sharedMaxAge);
                    break;

                default:
                    cc.Extensions.Add(nameValue); // success is always true
                    break;
                }

                if (!success)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 39
0
 internal static int GetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue, out CacheControlHeaderValue parsedValue)
 {
 }