【问题标题】:Cache control is not working in asp.net core 2.0 application缓存控制在 asp.net core 2.0 应用程序中不起作用
【发布时间】:2019-03-04 09:04:14
【问题描述】:

我通过 IIS 10 托管了一个网站,并在配置文件的下方添加了用于缓存静态内容的部分。

<configuration>
  <system.webServer>
    <staticContent>
  <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" cacheControlCustom="public" />
  </staticContent>...

下面是startup.cs文件部分

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var options = new RewriteOptions()
   .AddRedirect("rent/(.*)", "/$1")
   .AddRedirect("explore/(.*)", "/$1"); 
    app.UseRewriter(options);
    app.UseMyMiddleware();

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            const int durationInSeconds = 60 * 60 * 7;
            ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
        }
    });
}

但是,它不会在任何静态资源(如图像、js、css 文件)的响应标头中添加缓存控制。

谁能帮帮我?如果需要一些具体信息,请告诉我,我会更新。

【问题讨论】:

  • 自己发现了问题。我用了 app.UseStaticFiles();,空一个。
  • 请将其作为答案发布,这样这个问题就会从未回答的队列中移出。
  • 好的@ChrisPratt

标签: .net iis asp.net-core browser-cache cache-control


【解决方案1】:

我调用了两次UseStaticFiles 函数。评论默认的解决了这个问题。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var options = new RewriteOptions()
   .AddRedirect("rent/(.*)", "/$1")
   .AddRedirect("explore/(.*)", "/$1"); 
    app.UseRewriter(options);
    app.UseMyMiddleware();

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    //app.UseStaticFiles(); // commenting this fixed the issue.
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            const int durationInSeconds = 60 * 60 * 7;
            ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                "public,max-age=" + durationInSeconds;
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2018-02-08
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多