在 Asp.net Core 中更改静态文件的标题 [英] Change the headers of static files in Asp.net Core

查看:18
本文介绍了在 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.

这篇关于在 Asp.net Core 中更改静态文件的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆