如何将css,js或图像文件缓存到asp.net核心

时间:2016-06-08 15:08:07

标签: asp.net-core asp.net-core-mvc

间歇性代理导致我的页面被我部署的asp.net核心站点缓存。 Web服务器没有缓存页面。

我添加了请求和响应缓存,以防止此代理导致的任何缓存

在我的Startup.cs

        app.UseStaticFiles();

        app.UseIdentity();

        app.Use(async (context, next) =>
        {
            context.Response.Headers.Append("Cache-Control", "no-cache");
            context.Response.Headers.Append("Cache-Control", "private, no-store");
            context.Request.Headers.Append("Cache-Control", "no-cache");
            context.Request.Headers.Append("Cache-Control", "private, no-store");
            await next();
        });

我可以在fiddler中看到,我的页面以及javascript文件,css文件和图像文件中都没有添加缓存标头。

  1. 如何限制此缓存标题仅适用于asp.net mvc页面,因此这些没有缓存标头不会在fiddler中显示非页面文件,如js,css和图像文件

  2. 有没有办法让HTTP请求css和js文件不检查服务器上是否存在每个请求的文件,而只是浏览器版本用于第一次获取这些文件。我问的原因是,在重负载(1000个用户)我在Fiddler我发现我为我的css,js和图像文件得到了HTTPGET的404错误,所以我试图限制对这些资源的请求数量。当请求成功(没有加载)时,我得到304个响应(未修改)。是否有办法告诉浏览器不首先发出请求并使用本地缓存版本。

3 个答案:

答案 0 :(得分:13)

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse =
        r =>
        {
            string path = r.File.PhysicalPath;
            if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg"))
            {
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);
                r.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0"));
            }
        }
});

答案 1 :(得分:1)

这是一种适合您的方法。此示例将浏览器将css和js文件设置为缓存7天,并将非css,js和images设置为不具有缓存标头。另外需要注意的是,只需要在响应上设置缓存控制头是Asp.NET Core。

        app.Use(async (context, next) =>
        {
            string path = context.Request.Path;

            if(path.EndsWith(".css") || path.EndsWith(".js")) {

                //Set css and js files to be cached for 7 days
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);     //7 days
                context.Response.Headers.Append("Cache-Control", "max-age="+ maxAge.TotalSeconds.ToString("0")); 

            } else if(path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png")) {
                //custom headers for images goes here if needed

            } else {
                //Request for views fall here.
                context.Response.Headers.Append("Cache-Control", "no-cache");
                context.Response.Headers.Append("Cache-Control", "private, no-store");

            }
            await next();
        });

答案 2 :(得分:0)

通过app.UseStaticFiles的另一种解决方案

 app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                const int durationInSeconds = 60 * 60 * 24;
                ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                    "public,max-age=" + durationInSeconds;
            }
        });

您必须添加该库;

using Microsoft.Net.Http.Headers;