通过使用Response.OnStarting事件在中间件的末尾手动添加Cache-Control标头。
示例代码:
public class CacheMiddleware
{
private readonly RequestDelegate _next;
public CacheMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Call the next middleware in the pipeline
await _next(context);
// Set the Cache-Control header if it hasn't already been set
if (!context.Response.Headers.ContainsKey("Cache-Control"))
{
context.Response.Headers.Add("Cache-Control", "max-age=3600");
}
}
}
在Startup.cs文件中,将CacheMiddleware添加到中间件管道中:
app.UseMiddleware();