更改 Asp.net Core 中静态文件的标头

问题描述:

我正在使用包 Microsoft.AspNet.StaticFiles 并在 Startup.cs 中将其配置为 app.UseStaticFiles().如何更改已交付文件的标题?我想为图片、css 和 js 设置缓存过期等.

I am using package Microsoft.AspNet.StaticFiles and configuring it in Startup.cs as app.UseStaticFiles(). How can I change the headers of the delivered files ? I want to set cache expiry etc for images, css and js.

您可以使用 StaticFileOptions,它包含一个事件处理程序,在每次请求静态文件时调用该处理程序.

You can use StaticFileOptions, which contains an event handler that is called on each request of a static file.

您的 Startup.cs 应如下所示:

Your Startup.cs should look something like this:

// Add static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = (context) =>
    {
        // Disable caching of all static files.
        context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
        context.Context.Response.Headers["Pragma"] = "no-cache";
        context.Context.Response.Headers["Expires"] = "-1";
    }
});

当然,您可以修改上面的代码来检查内容类型,并且只修改 JS 或 CSS 或任何您想要的标题.

You can, of course, modify the above code to check the content type and only modify headers for JS or CSS or whatever you want.