asp.net-core – 更改Asp.net Core中静态文件的标题

我正在使用Microsoft.AspNet.StaticFiles包并在Startup.cs中将其配置为app.UseStaticFiles().如何更改已传送文件标题?我想为图像,css和js设置缓存到期等.

解决方法

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

你的Startup.cs应该是这样的:

// 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或任何您想要的标题.

相关文章

本文将从上往下,循序渐进的介绍一系列相关.NET的概念,先从...
基于 .NET 的一个全新的、好用的 PHP SDK + Runtime: Pe...
.NET 异步工作原理介绍。
引子 .NET 6 开始初步引入 PGO。PGO 即 Profile Guided Opti...
前言 2021/4/8 .NET 6 Preview 3 发布,这个版本的改进大多来...
前言 开头防杠:.NET 的基础库、语言、运行时团队从来都是相...