private void AddToCache(string resource, HttpResponseMessage response) { // Reads the cache-control header from the response var cacheHeader = response.Headers.FirstOrDefault(h => h.Key.Equals("cache-control", StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(cacheHeader.Key)) { return; } // Parses the cache-control value and extracts maxage from it var maxAge = CacheControlHeaderValue.Parse(cacheHeader.Value.FirstOrDefault()).MaxAge; if (maxAge.HasValue) { // Adds the response to the cache if it has a max-age value _cache.Add(key: resource, value: response, ttl: maxAge.Value); } }
public void Equals_CompareCollectionFieldsSet_MatchExpectation() { CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue(); cacheControl1.NoCache = true; cacheControl1.NoCacheHeaders.Add("token2"); Assert.False(cacheControl1.Equals(null), "Compare with 'null'"); cacheControl2.NoCache = true; cacheControl2.NoCacheHeaders.Add("token1"); cacheControl2.NoCacheHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl2, false); cacheControl1.NoCacheHeaders.Add("token1"); CompareValues(cacheControl1, cacheControl2, true); // Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders // have the same values, the hash code will be different. cacheControl3.Private = true; cacheControl3.PrivateHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl3, false); cacheControl4.Private = true; cacheControl4.PrivateHeaders.Add("token3"); CompareValues(cacheControl3, cacheControl4, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl1, cacheControl5, false); cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV")); cacheControl6.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl5, cacheControl6, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV")); CompareValues(cacheControl5, cacheControl6, true); }
public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero() { CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoCache = true; CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected); expected = new CacheControlHeaderValue(); expected.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Add("token2"); CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected); expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MaxAge = new TimeSpan(0, 0, 125); expected.MaxStale = true; CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected); expected = new CacheControlHeaderValue(); expected.MinFresh = new TimeSpan(0, 0, 123); expected.NoTransform = true; expected.OnlyIfCached = true; expected.Extensions.Add(new NameValueHeaderValue("custom")); CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected); expected = new CacheControlHeaderValue(); expected.Public = true; expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.MustRevalidate = true; expected.ProxyRevalidate = true; expected.Extensions.Add(new NameValueHeaderValue("c", "d")); expected.Extensions.Add(new NameValueHeaderValue("a", "b")); CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=b", 0, null, 72, expected); expected = new CacheControlHeaderValue(); expected.Private = true; expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890); expected.MaxAge = new TimeSpan(0, 0, 987654321); CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected); }
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 }); }
public CacheControl(HttpCachedClient parent, HttpResponseMessage response) { var headers = response.Headers; var contentHeaders = response.Content.Headers; Date = headers.Date ?? DateTimeOffset.UtcNow; Value = headers.CacheControl ?? CacheControlHeaderValue.Parse(headers.Pragma.ToString()); ShouldCache = Value.Public || (Value.Private && parent.Shared) || !Value.NoStore; // 4.2.1. Calculating Freshness Lifetime FreshnessLifetime = parent.Shared && Value.SharedMaxAge != null && Value.SharedMaxAge.Value.TotalSeconds != 0 ? Value.SharedMaxAge : Value.MaxAge != null && Value.MaxAge.Value.TotalSeconds != 0 ? Value.MaxAge : contentHeaders.Expires != null ? (TimeSpan?)contentHeaders.Expires.Value.Subtract(Date) : contentHeaders.LastModified != null ? (TimeSpan?)TimeSpan.FromSeconds(contentHeaders.LastModified.Value.Subtract(Date).TotalSeconds / 10) : null; Validation = !Value.NoCache && (Value.MaxAge == null || Value.MaxAge.Value.TotalSeconds != 0) ? (Func <Func <Task <HttpResponseMessage> >, HttpRequestMessage, Task <HttpResponseMessage> >)null : headers.ETag != null ? (b, r) => IfNoneMatch(b, r, headers.ETag) : contentHeaders.LastModified != null ? (b, r) => IfModifiedSince(b, r, contentHeaders.LastModified.Value) : (Func <Func <Task <HttpResponseMessage> >, HttpRequestMessage, Task <HttpResponseMessage> >)null; }
/// <summary> /// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the /// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion. /// </summary> /// <param name="httpContextBase">The HTTP context base.</param> /// <param name="response">The response to convert.</param> /// <param name="request">The request (which will be disposed).</param> /// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> /// including writing out any entity body.</returns> internal static Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request) { Contract.Assert(httpContextBase != null); Contract.Assert(request != null); // A null response creates a 500 with no content if (response == null) { CreateEmptyErrorResponse(httpContextBase.Response); return(TaskHelpers.Completed()); } CopyResponseStatusAndHeaders(httpContextBase, response); CacheControlHeaderValue cacheControl = response.Headers.CacheControl; // TODO 335085: Consider this when coming up with our caching story if (cacheControl == null) { // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header. // However, we don't want requests to be cached by default. // If nobody set an explicit CacheControl then explicitly set to no-cache to override the // default behavior. This will cause the following response headers to be emitted: // Cache-Control: no-cache // Pragma: no-cache // Expires: -1 httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache); } // Asynchronously write the response body. If there is no body, we use // a completed task to share the Finally() below. // The response-writing task will not fault -- it handles errors internally. Task writeResponseContentTask = (response.Content == null) ? TaskHelpers.Completed() : WriteResponseContentAsync(httpContextBase, response, request); return(writeResponseContentTask.Finally(() => { request.DisposeRequestResources(); request.Dispose(); response.Dispose(); })); }
/// <summary> /// Sets the 'Cache-Control' header to 'no-cache, no-store' and 'Pragma' header to 'no-cache' overriding any user set value. /// </summary> /// <param name="httpContext">The <see cref="HttpContext"/>.</param> protected virtual void SetDoNotCacheHeaders(HttpContext httpContext) { var logWarning = false; var responseHeaders = httpContext.Response.Headers; if (responseHeaders.TryGetValue(HeaderNames.CacheControl, out var cacheControlHeader) && CacheControlHeaderValue.TryParse(cacheControlHeader.ToString(), out var cacheControlHeaderValue)) { // If the Cache-Control is already set, override it only if required if (!cacheControlHeaderValue.NoCache || !cacheControlHeaderValue.NoStore) { logWarning = true; responseHeaders.CacheControl = "no-cache, no-store"; } } else { responseHeaders.CacheControl = "no-cache, no-store"; } if (responseHeaders.TryGetValue(HeaderNames.Pragma, out var pragmaHeader) && pragmaHeader.Count > 0) { // If the Pragma is already set, override it only if required if (!string.Equals(pragmaHeader[0], "no-cache", StringComparison.OrdinalIgnoreCase)) { logWarning = true; httpContext.Response.Headers.Pragma = "no-cache"; } } else { httpContext.Response.Headers.Pragma = "no-cache"; } // Since antiforgery token generation is not very obvious to the end users (ex: MVC's form tag generates them // by default), log a warning to let users know of the change in behavior to any cache headers they might // have set explicitly. if (logWarning) { _logger.ResponseCacheHeadersOverridenToNoCache(); } }
static Util() { utf8Encoding = new UTF8Encoding(false); lastTimeStamp = DateTime.UtcNow.Ticks; xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.Encoding = utf8Encoding; xmlWriterSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; xmlWriterSettingsFragment = new XmlWriterSettings(); xmlWriterSettingsFragment.Encoding = utf8Encoding; xmlWriterSettingsFragment.NamespaceHandling = NamespaceHandling.OmitDuplicates; xmlWriterSettingsFragment.ConformanceLevel = ConformanceLevel.Fragment; xmlReaderSettings = new XmlReaderSettings(); xmlReaderSettings.IgnoreWhitespace = true; xmlReaderSettings.CheckCharacters = false; xmlParserContext = new XmlParserContext(null, null, "en", XmlSpace.Default, utf8Encoding); noCacheCtrl = new CacheControlHeaderValue { NoCache = true, NoStore = true }; iso8601DateFormats = new string[] { "yyyy-MM-ddTHH:mm:ss.FFFzzz", "yyyy-MM-ddTHH:mm:ss.FFFzz", "yyyy-MM-ddTHH:mm:ss.FFFZ", "yyyy-MM-ddTHH:mm:ss.FFFFZ", "yyyy-MM-ddTHH:mm:ss.FFFFFZ", "yyyy-MM-ddTHH:mm:ss.FFFFFFZ", "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ", // Extended formats "yyyy-MM-ddTHH:mm:sszzz", "yyyy-MM-ddTHH:mm:sszz", "yyyy-MM-ddTHH:mm:ssZ", // All of the above with reduced accuracy "yyyy-MM-ddTHH:mmzzz", "yyyy-MM-ddTHH:mmzz", "yyyy-MM-ddTHH:mmZ", }; }
internal static void HandleEtag(HttpContext httpContext, string calculatedEtag) { if (httpContext.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && Ccf.Ck.Utilities.Generic.Utilities.WithQuotes(calculatedEtag) == etag) { //there is etag and it is equal httpContext.Response.StatusCode = StatusCodes.Status304NotModified; return; } else { //there is NO etag OR it is NOT equal } CacheControlHeaderValue cacheControlHeaderValue = new CacheControlHeaderValue(); cacheControlHeaderValue.MaxAge = TimeSpan.FromDays(365); cacheControlHeaderValue.Public = true; httpContext.Response.GetTypedHeaders().CacheControl = cacheControlHeaderValue; httpContext.Response.Headers.Add(HeaderNames.ETag, new[] { Ccf.Ck.Utilities.Generic.Utilities.WithQuotes(calculatedEtag) }); }
private static void NoCacheHeaders(ActionExecutedContext context) { var headerCache = new CacheControlHeaderValue() { NoCache = true }; context.HttpContext.Response.Headers.Add("Cache-Control", headerCache.ToString()); StringValues dateValue; context.HttpContext.Response.Headers.TryGetValue("Date", out dateValue); if (string.IsNullOrEmpty(dateValue)) { context.HttpContext.Response.Headers.Add("Date", DateTimeOffset.UtcNow.ToString()); } context.HttpContext.Response.Headers.Add("Expires", DateTimeOffset.UtcNow.ToString()); }
public CDOSession(CDOSessionOptions options) { Options = options; Instance = this; //used by cdo when no session object is passed //init httpclient HttpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }); //HttpClient = new HttpClient(new HttpClientHandler() { SslProtocols = _options.SslProtocols }); //this is not supported in older frameworks & problematic in Outlook VSTO ServicePointManager.SecurityProtocol = Options.SecurityProtocol; HttpClient.DefaultRequestHeaders.ConnectionClose = false; HttpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); HttpClient.DefaultRequestHeaders.Pragma.Add(NameValueHeaderValue.Parse("no-cache")); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Task.Factory.StartNew(() => NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged).Wait(); }
public HttpCacheControlPolicyAttribute(bool isPrivate, int maxAgeInSeconds, bool mustRevalidate = true, bool noCache = false, bool noTransform = false, bool nostore = false) : this() { // copy values to the header _cacheControl = new CacheControlHeaderValue() { Private = isPrivate, Public = !isPrivate, MustRevalidate = mustRevalidate, MaxAge = TimeSpan.FromSeconds(maxAgeInSeconds), NoCache = noCache, NoTransform = noTransform, NoStore = nostore }; }
/// <summary> /// Applies the <see cref="CachePolicy"/> <c>MaxAge</c> value to the given <paramref name="response"/>. /// </summary> /// <param name="response">The current <see cref="HttpResponseMessage"/>.</param> protected virtual void SetMaxAge(HttpResponseMessage response) { if (response == null) { throw new ArgumentNullException("response"); } if (this.Policy.MaxAge.HasValue) { CacheControlHeaderValue cacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(); cacheControl.MaxAge = this.Policy.MaxAge; response.Headers.CacheControl = cacheControl; // If there is an HTTP response content then set Expires header field if (response.Content != null) { response.Content.Headers.Expires = DateTimeOffset.UtcNow + this.Policy.MaxAge.Value; } } }
private void ApplyCacheHeaders(HttpResponseMessage response, CacheTime cacheTime) { if (cacheTime.ClientTimeSpan > TimeSpan.Zero || MustRevalidate) { var cachecontrol = new CacheControlHeaderValue { MaxAge = cacheTime.ClientTimeSpan, MustRevalidate = MustRevalidate }; response.Headers.CacheControl = cachecontrol; } else if (NoCache) { response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true }; response.Headers.Add("Pragma", "no-cache"); } }
public void ToString_NegativeValues_UsesMinusSignRegardlessOfCurrentCulture() { RemoteExecutor.Invoke(() => { var cacheControl = new CacheControlHeaderValue() { MaxAge = new TimeSpan(0, 0, -1), MaxStale = true, MaxStaleLimit = new TimeSpan(0, 0, -2), MinFresh = new TimeSpan(0, 0, -3), SharedMaxAge = new TimeSpan(0, 0, -4) }; var ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.NegativeSign = "n"; CultureInfo.CurrentCulture = ci; Assert.Equal("max-age=-1, s-maxage=-4, max-stale=-2, min-fresh=-3", cacheControl.ToString()); }).Dispose(); }
public void Parse_Invalid() { try { CacheControlHeaderValue.Parse("audio/"); Assert.Fail("#1"); } catch (FormatException) { } try { CacheControlHeaderValue.Parse("max-age="); Assert.Fail("#2"); } catch (FormatException) { } try { CacheControlHeaderValue.Parse("me="); Assert.Fail("#3"); } catch (FormatException) { } }
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 void ConfigureHttpClient(NexusNodeEndpoint endpoint) { if (_client == null) { throw new NullReferenceException("Http client is null"); } if (endpoint == null) { throw new ArgumentException("Parameters are missing"); } if (string.IsNullOrWhiteSpace(endpoint.Url)) { throw new ArgumentException("URL is missing"); } if (string.IsNullOrWhiteSpace(endpoint.Username)) { throw new ArgumentException("Username is missing"); } if (string.IsNullOrWhiteSpace(endpoint.Password)) { throw new ArgumentException("Password is missing"); } var uriResult = Uri.TryCreate(endpoint.Url, UriKind.Absolute, out var baseUri) && (baseUri.Scheme == Uri.UriSchemeHttp || baseUri.Scheme == Uri.UriSchemeHttps); if (!uriResult) { throw new Exception("Url is not valid"); } var auth64 = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{endpoint.Username}:{endpoint.Password}")); _client.BaseAddress = baseUri; _client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {auth64}"); _client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); }
public void InitClient(CookieContainer cookieContainer) { if (client != null) { client.Dispose(); } if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { var cookies = cookieContainer.List(); cookieHandler = new NativeCookieHandler(); cookieHandler.SetCookies(cookieContainer.List()); handler = new NativeMessageHandler(false, false, cookieHandler) { AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; } else { handler = new HttpClientHandler { CookieContainer = cookieContainer, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; } client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeout_in_seconds), DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, must-revalidate"), } }; client.DefaultRequestHeaders.UserAgent.ParseAdd("Tatoeba.Mobile/1.1"); }
private void AddToCache(string resource, HttpResponseMessage response) { var cacheHeader = response .Headers .FirstOrDefault(h => h.Key == "cache-control"); if (string.IsNullOrEmpty(cacheHeader.Key)) { return; } var maxAge = CacheControlHeaderValue .Parse(cacheHeader.Value.ToString()) .MaxAge; if (maxAge.HasValue) { _cache.Add(key: resource, value: response, ttl: maxAge.Value); } }
public static async Task <string> Get(string url, IEnumerable <KeyValuePair <string, string> > header = null, bool isBrowser = false) { try { var handler = new HttpClientHandler() { UseCookies = false }; HttpClient hc = new HttpClient(handler); CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); cacheControl.NoCache = true; cacheControl.NoStore = true; hc.DefaultRequestHeaders.CacheControl = cacheControl; if (isBrowser) { hc.DefaultRequestHeaders.Add("user-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36 Qiyu/2.1.1.1"); } else { hc.DefaultRequestHeaders.Add("user-Agent", "asusrouter-Android-DUTUtil-1.0.0.108"); } hc.DefaultRequestHeaders.Add("Cookie", Cookie); if (header != null) { foreach (var item in header) { hc.DefaultRequestHeaders.Add(item.Key, item.Value); } } var res = await hc.GetAsync(url); var json = await res.Content.ReadAsStringAsync(); return(json); } catch (Exception e) { return(null); } }
public void Should_return_Stale_header_if_stale_by_max_age() { // Arrange var cacheControl = new CacheControlHeaderValue { MaxStale = true, MaxStaleLimit = TimeSpan.FromSeconds(15), MinFresh = TimeSpan.FromSeconds(20) }; var cacheItem = new WebApiCacheItem { CreatedTime = DateTime.UtcNow.AddSeconds(-11), MaxAge = 10, StaleWhileRevalidate = 5, IgnoreRevalidationRequest = true, ResponseCharSet = "UTF8", ResponseMediaType = "text/json", Content = new byte[0], Key = "CacheKey" + Guid.NewGuid() }; Global.Cache.PhoenixFireCage[cacheItem.Key] = new Phoenix(NSubstitute.Substitute.For <_IInvocation>(), new CacheItem()); var request = UnitTestHelper.GetMessage(); var svc = new CacheResponseBuilder { }; // Action var response = svc.GetResponse(cacheControl, cacheItem, request); // Assert Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("Cache freshness lifetime not qualified", response.Headers.GetValues("X-Flatwhite-Warning").First()); Assert.AreEqual("Response is Stale", response.Headers.GetValues("X-Flatwhite-Warning").Last()); Assert.AreEqual($"110 - \"Response is Stale\"", response.Headers.GetValues("Warning").Last()); Assert.AreEqual("stale-while-revalidate", response.Headers.CacheControl.Extensions.ToList().First().Name); Assert.AreEqual(cacheItem.ResponseMediaType, response.Content.Headers.ContentType.MediaType); Assert.AreEqual(cacheItem.ResponseCharSet, response.Content.Headers.ContentType.CharSet); }
private async Task <HttpResponseInfo> MakeHttpRequest(HttpRequestInfo requestInfo) { SendingRemoteHttpRequestEventArgs eventArgs = new SendingRemoteHttpRequestEventArgs(null, requestInfo.RequestBody); this.OnSendingRemoteHttpRequest(eventArgs); HttpMethod method = new HttpMethod(requestInfo.HttpMethod); HttpRequestMessage requestMessage = new HttpRequestMessage(method, requestInfo.FullUri); if (requestInfo.HttpMethod == CommandInfo.GetCommand) { CacheControlHeaderValue cacheControlHeader = new CacheControlHeaderValue(); cacheControlHeader.NoCache = true; requestMessage.Headers.CacheControl = cacheControlHeader; } if (requestInfo.HttpMethod == CommandInfo.PostCommand) { MediaTypeWithQualityHeaderValue acceptHeader = new MediaTypeWithQualityHeaderValue(JsonMimeType); acceptHeader.CharSet = Utf8CharsetType; requestMessage.Headers.Accept.Add(acceptHeader); byte[] bytes = Encoding.UTF8.GetBytes(eventArgs.RequestBody); requestMessage.Content = new ByteArrayContent(bytes, 0, bytes.Length); MediaTypeHeaderValue contentTypeHeader = new MediaTypeHeaderValue(JsonMimeType); contentTypeHeader.CharSet = Utf8CharsetType; requestMessage.Content.Headers.ContentType = contentTypeHeader; } HttpResponseMessage responseMessage = await this.client.SendAsync(requestMessage); HttpResponseInfo httpResponseInfo = new HttpResponseInfo(); httpResponseInfo.Body = await responseMessage.Content.ReadAsStringAsync(); httpResponseInfo.ContentType = responseMessage.Content.Headers.ContentType.ToString(); httpResponseInfo.StatusCode = responseMessage.StatusCode; return(httpResponseInfo); }
/// <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); }
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); }
static HttpClient CreateAndConfigureHttpClient() { IWebBrowser webBrowser = new ChromiumWebBrowser( Configurations.PathToChromiumExecutable, Configurations.WorkingDirectory ); var userAgentString = webBrowser.GetUserAgentString(); webBrowser.Dispose(); var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br"); httpClient.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9"); httpClient.DefaultRequestHeaders.Upgrade.ParseAdd("1"); httpClient.DefaultRequestHeaders.Pragma.ParseAdd("no-cache"); httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgentString); httpClient.Timeout = Configurations.HttpRequestTimeout; return(httpClient); }
protected virtual void ApplyCacheHeaders(HttpResponseMessage response, CacheTime cacheTime) { if (cacheTime.ClientTimeSpan > TimeSpan.Zero || MustRevalidate || AllowedCacheLocation != AllowedCacheLocation.Undefined) { var cachecontrol = new CacheControlHeaderValue { MaxAge = cacheTime.ClientTimeSpan, MustRevalidate = MustRevalidate, Private = AllowedCacheLocation == AllowedCacheLocation.Private, Public = AllowedCacheLocation == AllowedCacheLocation.Public }; response.Headers.CacheControl = cachecontrol; } else if (NoCache) { response.Headers.CacheControl = new CacheControlHeaderValue { NoCache = true }; response.Headers.Add("Pragma", "no-cache"); } }
public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); Assert.Equal("", cacheControl.ToString()); // Note that we allow all combinations of all properties even though the RFC specifies rules what value // can be used together. // Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the // caller needs to set the bool property in order for the collection to be populated as string. // Cache Request Directive sample cacheControl.NoStore = true; Assert.Equal("no-store", cacheControl.ToString()); cacheControl.NoCache = true; Assert.Equal("no-store, no-cache", cacheControl.ToString()); cacheControl.MaxAge = new TimeSpan(0, 1, 10); Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString()); cacheControl.MaxStale = true; Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString()); cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString()); cacheControl.MinFresh = new TimeSpan(0, 3, 0); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.NoTransform = true; Assert.Equal("no-transform", cacheControl.ToString()); cacheControl.OnlyIfCached = true; Assert.Equal("no-transform, only-if-cached", cacheControl.ToString()); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue")); Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); Assert.Equal("custom", cacheControl.ToString()); }
public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation() { // Verify that different bool fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[9]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].ProxyRevalidate = true; values[1].NoCache = true; values[2].NoStore = true; values[3].MaxStale = true; values[4].NoTransform = true; values[5].OnlyIfCached = true; values[6].Public = true; values[7].Private = true; values[8].MustRevalidate = true; // Only one bool field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareValues(values[i], values[j], false); } } } // Validate that two instances with the same bool fields set are equal. values[0].NoCache = true; CompareValues(values[0], values[1], false); values[1].ProxyRevalidate = true; CompareValues(values[0], values[1], true); }
/// <summary> /// Sets whether an HTTP client is willing to accept a cached response. /// </summary> /// <param name="response">The response message.</param> /// <returns>A <see cref="HttpResponseMessage"/> instance that represents a response message.</returns> public static HttpResponseMessage SetNoCache(this HttpResponseMessage response) { if (response == null) { throw new ArgumentNullException("response"); } CacheControlHeaderValue cc = response.Headers.CacheControl; if (cc == null) { cc = new CacheControlHeaderValue(); response.Headers.CacheControl = cc; } // Google sample. cc.NoCache = true; cc.MaxAge = TimeSpan.Zero; cc.NoStore = true; cc.MustRevalidate = true; return(response); }