缓存控制在asp.net core 2.0应用程序中不起作用

问题描述 投票:0回答:1

我在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;
        }
    });
}

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

谁能帮我吗?如果需要某些特定信息,请告诉我,我将更新有问题。

.net iis asp.net-core browser-cache cache-control
1个回答
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;
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.