英文:
Cache-Control is not respected in ASP.NET Core Middleware
问题
我有这个中间件:
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().Contains("image/resize"))
{
context.Response.Headers["Cache-Control"] = "max-age=31536000";
}
else
{
context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Expires"] = "0";
}
await next.Invoke();
});
问题是当我请求一张图片时,我得到这个响应头:
> cache-control: public,max-age=30
如果我请求返回 JSON 的 API,else
块就能工作。缓存头被正确设置。
但对于提供的图像,缓存没有正确设置。
可能出了什么问题?我怎么修复这个?
更新
这是这个中间件之后在流水线中的我的代码:
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(options =>
{
options.MapRoute("Default", "{controller=Default}/{action=Index}/{id?}");
});
英文:
I have this middleware:
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().Contains("image/resize"))
{
context.Response.Headers["Cache-Control"] = "max-age=31536000";
}
else
{
context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Expires"] = "0";
}
await next.Invoke();
});
The problem is that when I request an image, I get this response header:
> cache-control: public,max-age=30
If I request an API that returns JSON, the else
block works. Cache headers are set correctly.
But for images that are served, the cache is not set correctly.
What might be wrong? How can I fix this?
Update
These are my codes after this middleware in the pipeline:
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(options =>
{
options.MapRoute("Default", "{controller=Default}/{action=Index}/{id?}");
});
答案1
得分: 1
正确的顺序应该像下面这样:
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(options =>
{
options.MapRoute("Default", "{controller=Default}/{action=Index}/{id?}");
});
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().Contains("image/resize"))
{
context.Response.Headers["Cache-Control"] = "max-age=31536000";
}
else
{
context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Expires"] = "0";
}
await next.Invoke();
});
英文:
The correct order should be like below:
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(options =>
{
options.MapRoute("Default", "{controller=Default}/{action=Index}/{id?}");
});
app.Use(async (context, next) =>
{
if (context.Request.Path.ToString().Contains("image/resize"))
{
context.Response.Headers["Cache-Control"] = "max-age=31536000";
}
else
{
context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Expires"] = "0";
}
await next.Invoke();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论