Пример #1
0
        /// <summary>
        /// Sets the cache headers for static files.
        /// </summary>
        /// <param name="context">The static file response context to set the headers for.</param>
        private void SetCacheHeaders(StaticFileResponseContext context)
        {
            var maxAge = TimeSpan.FromDays(7);

            if (context.File.Exists && HostingEnvironment.IsProduction())
            {
                string?extension = Path.GetExtension(context.File.PhysicalPath);

                // These files are served with a content hash in the URL so can be cached for longer
                bool isScriptOrStyle =
                    string.Equals(extension, ".css", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(extension, ".js", StringComparison.OrdinalIgnoreCase);

                if (isScriptOrStyle)
                {
                    maxAge = TimeSpan.FromDays(365);
                }
            }

            var headers = context.Context.Response.GetTypedHeaders();

            headers.CacheControl = new CacheControlHeaderValue()
            {
                MaxAge = maxAge,
            };
        }
Пример #2
0
        private static void SetCacheControlHeader(StaticFileResponseContext context)
        {
            const int durationInSeconds = 60 * 60 * 24;

            context.Context.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
        }
        private void OnPrepareResponse(StaticFileResponseContext context)
        {
            bool setCachingHeaders = false;

            switch (_staticFilesSettings.CacheMode)
            {
            case StaticFileCacheMode.None:
                return;

            case StaticFileCacheMode.All:
                setCachingHeaders = true;
                break;

            case StaticFileCacheMode.OnlyVersionedFiles:
                // only cache resources that use the asp-append-version parameter convention
                setCachingHeaders = !string.IsNullOrEmpty(context.Context.Request.Query["v"]);
                break;

            default:
                throw new InvalidOperationException("StaticFileCacheMode not regonised: " + _staticFilesSettings.CacheMode);
            }

            if (!setCachingHeaders)
            {
                return;
            }

            // cache for 1 year
            context.Context.Response.Headers[HeaderNames.CacheControl] = new[] { "public,max-age=" + _staticFilesSettings.MaxAge };
        }
Пример #4
0
        private static void OnPrepareResponse(StaticFileResponseContext context)
        {
            var file     = context.File;
            var request  = context.Context.Request;
            var response = context.Context.Response;

            if (file.Name.EndsWith(".gz"))
            {
                response.Headers[HeaderNames.ContentEncoding] = "gzip";
                return;
            }

            var acceptEncoding = (string)request.Headers[HeaderNames.AcceptEncoding];

            if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return;
            }

            if (!File.Exists(file.PhysicalPath + ".gz"))
            {
                return;
            }

            response.StatusCode = (int)HttpStatusCode.MovedPermanently;
            response.Headers[HeaderNames.Location] = request.Path.Value + ".gz";
        }
        private static void CacheStaticContent(StaticFileResponseContext ctx)
        {
            const int durationInSeconds = 60 * 60 * 24 * 365;

            ctx.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
        }
Пример #6
0
        /// <summary>
        /// 设置cache control
        /// </summary>
        /// <param name="context"></param>
        public static void SetCacheControl(StaticFileResponseContext context)
        {
            int second = 365 * 24 * 60 * 60;

            context.Context.Response.Headers.Add("Cache-Control", new[] { "public,max-age=" + second });
            context.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddYears(1).ToString("R") }); // Format RFC1123
        }
 private static void NoCacheOnIndex(StaticFileResponseContext context)
 {
     if (context.File.Name == "index.html")
     {
         context.Context.Response.Headers.Add("Cache-Control", new[] { "no-cache", "no-store", "must-revalidate" });
         context.Context.Response.Headers.Add("Pragma", new[] { "no-cache" });
         context.Context.Response.Headers.Add("Expires", new[] { "0" });
     }
 }
Пример #8
0
        private void PrepareStaticFileResponse(StaticFileResponseContext context)
        {
            var headers = context.Context.Response.Headers;

            headers
            .Add("cache-control", "private,max-age=31536000,immutable");
            headers
            .Add("x-content-type-options", "nosniff");
        }
 private static void ConfigureCacheControl(StaticFileResponseContext ctx)
 {
     if (ctx.File.Name.EndsWith(".clr", StringComparison.OrdinalIgnoreCase))
     {
         // Cache managed files for a year, based on this update:
         // https://github.com/nventive/Uno.Wasm.Bootstrap/commit/f4859452c715c54ac40b968a303a242b0399d59a
         ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=31536000");
     }
 }
Пример #10
0
        void staticFileResponse(StaticFileResponseContext context)
        {
            var commonSettings = EngineContext.Current.Resolve <CommonSettings>();

            if (!string.IsNullOrEmpty(commonSettings.StaticFilesCacheControl))
            {
                context.Context.Response.Headers.Append(HeaderNames.CacheControl, commonSettings.StaticFilesCacheControl);
            }
        }
Пример #11
0
        private static void PrepareResponse(StaticFileResponseContext context)
        {
            bool flag = LoggerExtensions.ContentTypes.Contains(context.Context.Response.ContentType);

            if (flag)
            {
                HttpResponse response = context.Context.Response;
                response.ContentType += "; charset=utf-8";
            }
        }
            private static StaticFileResponseContext ResponseContext()
            {
                var context = new StaticFileResponseContext(new DefaultHttpContext(),
                                                            file: new FakeFileInfo());

                //var type = context.GetType();
                //var property = type.GetProperty(nameof(context.Context));
                //property!.SetValue(context, new DefaultHttpContext(), null);

                return(context);
            }
Пример #13
0
        private static void SetCacheHeaders(StaticFileResponseContext ctx)
        {
            var typedHeaders = ctx.Context.Response.GetTypedHeaders();

            if (typedHeaders.CacheControl != null)
            {
                return;
            }
            typedHeaders.CacheControl = new CacheControlHeaderValue {
                NoCache = true
            };
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="staticFileResponseContext"></param>
        public static void OnPrepareResponse(StaticFileResponseContext staticFileResponseContext)
        {
            if (staticFileResponseContext == null ||
                staticFileResponseContext.File == null ||
                (!".nuspec".Equals(Path.GetExtension(staticFileResponseContext.File.Name), StringComparison.OrdinalIgnoreCase) && !".nupkg".Equals(Path.GetExtension(staticFileResponseContext.File.Name), StringComparison.OrdinalIgnoreCase)))
            {
                return;
            }

            var nuGetPackageIndex = staticFileResponseContext.Context.RequestServices.GetService <INuGetPackageIndex>();

            nuGetPackageIndex.IncrementDownloadCounter(staticFileResponseContext.File.PhysicalPath);
        }
Пример #15
0
            static void staticFileResponse(StaticFileResponseContext context)
            {
                if (!DataSettingsManager.DatabaseIsInstalled)
                {
                    return;
                }

                var commonSettings = EngineContext.Current.Resolve <CommonSettings>();

                if (!string.IsNullOrEmpty(commonSettings.StaticFilesCacheControl))
                {
                    context.Context.Response.Headers.Append(HeaderNames.CacheControl, commonSettings.StaticFilesCacheControl);
                }
            }
Пример #16
0
 private void AddFileCacheHeaders(StaticFileResponseContext context)
 {
     // If we see you have sha on the url we send aggresive cache values
     // otherwise we tell to not cache ever
     if (context.Context.Request.Query.ContainsKey(Constants.FileUrlShaKey))
     {
         // Cache for a year
         context.Context.Response.Headers["Cache-Control"] = "public, max-age=31536000";
     }
     else
     {
         context.Context.Response.Headers["Cache-Control"] = "no-cache";
         context.Context.Response.Headers["Pragma"]        = "no-cache";
         context.Context.Response.Headers["Expires"]       = "Thu, 01 Jan 1970 00:00:00 GMT";
     }
 }
 private static void SetCacheHeaders(StaticFileResponseContext ctx)
 {
     // By setting "Cache-Control: no-cache", we're allowing the browser to store
     // a cached copy of the response, but telling it that it must check with the
     // server for modifications (based on Etag) before using that cached copy.
     // Longer term, we should generate URLs based on content hashes (at least
     // for published apps) so that the browser doesn't need to make any requests
     // for unchanged files.
     var headers = ctx.Context.Response.GetTypedHeaders();
     if (headers.CacheControl == null)
     {
         headers.CacheControl = new CacheControlHeaderValue
         {
             NoCache = true
         };
     }
 }
Пример #18
0
        public bool CanCache(StaticFileResponseContext context)
        {
            //Static
            if (!_config.UseCacheStatic)
            {
                return(false);
            }
            string path = context.Context.Request.Path;

            if (!this.IsPathStatic(path))
            {
                return(false);
            }
            string queryString = context.Context.Request.QueryString.ToString();

            return(queryString.Contains("ab=" + _config.ApplicationBuild));
        }
Пример #19
0
        static void OnPrepareStaticFileResponse(StaticFileResponseContext staticFileContext)
        {
            var context = staticFileContext.Context;
            var req     = context.Request;
            var res     = context.Response;
            var headers = res.Headers;

            if (req.Query.ContainsKey("DX_HTTP_CACHE"))
            {
                headers["Cache-Control"] = "public, max-age=31536000";
            }
            else
            {
                headers["Cache-Control"] = "private, must-revalidate, max-age=0";
            }

            headers.Remove("ETag");
        }
        private static void GZipStaticContent(StaticFileResponseContext ctx)
        {
            var headers     = ctx.Context.Response.Headers;
            var contentType = headers["Content-Type"];

            if (contentType != "application/x-gzip" && !ctx.File.Name.EndsWith(".gz"))
            {
                return;
            }

            var fileNameToTry = ctx.File.Name.Substring(0, ctx.File.Name.Length - 3);

            if (new FileExtensionContentTypeProvider().TryGetContentType(fileNameToTry, out var mimeType))
            {
                headers.Add("Content-Encoding", "gzip");
                headers["Content-Type"] = mimeType;
            }
        }
Пример #21
0
 public void Prepare(IContentTypeProvider contentTypeProvider, StaticFileResponseContext staticFileResponseContext)
 {
     foreach (var compressionType in CompressedAlternativeFileProvider.CompressionTypes.Keys)
     {
         var fileExtension = CompressedAlternativeFileProvider.CompressionTypes[compressionType];
         if (staticFileResponseContext.File.Name.EndsWith(fileExtension, StringComparison.OrdinalIgnoreCase))
         {
             // we need to restore the original content type, otherwise it would be based on the compression type
             // (for example "application/brotli" instead of "text/html")
             if (contentTypeProvider.TryGetContentType(staticFileResponseContext.File.PhysicalPath.Remove(
                                                           staticFileResponseContext.File.PhysicalPath.Length - fileExtension.Length, fileExtension.Length), out var contentType))
             {
                 staticFileResponseContext.Context.Response.ContentType = contentType;
             }
             staticFileResponseContext.Context.Response.Headers.Add("Content-Encoding", new[] { compressionType });
         }
     }
 }
Пример #22
0
        // https://gunnarpeipman.com/aspnet-core-precompressed-files/
        public static void ServeGzipFiles(this StaticFileResponseContext context)
        {
            var headers     = context.Context.Response.Headers;
            var contentType = headers["Content-Type"];

            if (contentType != "application/x-gzip" && !context.File.Name.EndsWith(".gz"))
            {
                return;
            }

            var fileNameToTry = context.File.Name.Substring(0, context.File.Name.Length - 3);

            if (_fileTypes.TryGetContentType(fileNameToTry, out var mimeType))
            {
                headers.Add("Content-Encoding", "gzip");
                headers["Content-Type"] = mimeType;
            }
        }
Пример #23
0
        /// <summary>
        /// without this the browser did not seem to understand the gzipped file
        /// </summary>
        /// <param name="context"></param>
        public static void OnPrepareResponse(StaticFileResponseContext context)
        {
            var file     = context.File;
            var response = context.Context.Response;

            if (file.Name.EndsWith(".gz"))
            {
                response.Headers[HeaderNames.ContentEncoding] = "gzip";
                if (file.Name.EndsWith(".css.gz"))
                {
                    response.Headers[HeaderNames.ContentType] = "text/css";
                }
                if (file.Name.EndsWith(".js.gz"))
                {
                    response.Headers[HeaderNames.ContentType] = "application/javascript";
                }
                return;
            }
        }
Пример #24
0
 private void OnPrepareResponse(StaticFileResponseContext context)
 {
     context.Context.Response.Headers.Add("Cache-Control", new[] { "public,max-age=31536000" });
 }
Пример #25
0
 public void Prepare(IContentTypeProvider contentTypeProvider, StaticFileResponseContext staticFileResponseContext)
 {
 }
Пример #26
0
 public static void CacheFiles(this StaticFileResponseContext ctx)
 {
     ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=2592000");
     ctx.Context.Response.Headers.Append("Expires", DateTime.UtcNow.AddDays(30).ToString("R", CultureInfo.InvariantCulture));
 }
Пример #27
0
 static void preventCaching(StaticFileResponseContext http)
 {
     http.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
     http.Context.Response.Headers.Add("Expires", "-1");
 }