dotnet 核心设置 Cache-Control 无效

dotnet core setting Cache-Control has no effect

我已经配置了 dotnet 核心中间件来输出 Cache-Control headers。我希望缓存所有静态内容,但最特别的是几个 .png 文件。 缓存header没有被输出?我正在使用dotnet core 1.1.1。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = _ =>
            {
                var headers = _.Context.Request.GetTypedHeaders();
                headers.CacheControl = new CacheControlHeaderValue
                {
                    MaxAge = TimeSpan.FromHours(12)
                };
            }
        });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseIdentity();

    // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            "default",
            "{controller=Site}/{action=Site}/{id?}");
    });
}

代码被忽略,如下面的屏幕截图所示。

我也试过像这样显式添加 header,但我收到错误提示 header 已经存在。

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = _ =>
    {
        _.Context.Request.Headers.Add("Cache-Control", "public,max-age=60");
    }
});

不知怎么的,它被吃掉了。如果我设置断点,代码就会被调用。

您正在尝试操纵请求 header。

            var headers = _.Context.Request.GetTypedHeaders();
            headers.CacheControl = new CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromHours(12)
            };

浏览器需要响应 header,而不是请求 header。将 cache-control 添加到响应 header。不管是直接还是通过 CacheHeader 属性.

_.Context.Response.Headers.Append("Cache-Control", string.Format("public,max-age={0}", TimeSpan.FromHours(12).TotalSeconds));