英文:
Why does a permanent redirect has cache enabled but a temporary redirect doesn't have a cache?
问题
根据标题所说,为什么永久的301
重定向会显示页面的缓存版本,而临时的302
重定向不会?
如何强制永久的301
重定向始终在没有缓存的情况下显示?
在我的Program.cs
文件中,我拦截当前请求的URL路径并对其进行逻辑处理:
app.Use(async (context, next) =>
{
string strUrlPath = context.Request.Path.ToString().ToLowerInvariant();
switch (strUrlPath)
{
case string _ when strUrlPath.StartsWith("/deprecated_page"):
{
// 对访问次数进行逻辑处理,插入到数据库中
// 对尝试查看此页面的用户进行日志记录等操作
Log.LogContext().Warning(...);
// 重定向到404页面
context.Response.Redirect("/404", permanent: true);
return;
}
default:
await next();
break;
}
});
当作为参数传递的布尔标志permanent: true
时,页面将首先记录日志,但随后的请求将被缓存,不会执行任何逻辑或日志记录。
然而,如果标志设置为permanent: false
并且重定向是临时的,每个请求都会执行所有逻辑和日志记录。
为什么会有这种行为,如何强制在永久的301
重定向时在服务器端禁用缓存?
英文:
Like the title says, why does a permanent 301
redirect displays a cached version of the page while a temporary 302
doesn't ?
How can I force the permanent 301
redirect to always display without a cache ?
In my file Program.cs
, I intercept the current request url path and do logic on it
app.Use(async (context, next) =>
{
string strUrlPath = context.Request.Path.ToString().ToLowerInvariant();
switch (strUrlPath)
{
case string _ when strUrlPath.StartsWith("/deprecated_page"):
{
// Do some logic on number of times it was visited, insert into Database
// Do some logging on who attempted to view this page, ...etc.
Log.LogContext().Warning(...);
// redirect to 404 page
context.Response.Redirect("/404", permanent: true);
return;
}
default:
await next();
break;
}
});
When the boolean flag permanent: true
is passed as an argument, the page will first do logging but subsequent request will be cached and none of the logic nor the logging will be executed.
If however the flag is set to permanent: false
and the redirect is temporary, all logic and logging is done on each request.
Why is this a behaviour and how can I force to disable cache server side on a permanent 301
redirect ?
答案1
得分: 1
因为这就是“permanent”(永久)和“temporary”(临时)的意思。
永久重定向的目的是告诉客户端始终重定向到目标,因此它不需要再次检查。
如果你希望客户端始终发起第一个请求,那么你需要给他们一个临时重定向,这样他们每次都必须再次检查。
英文:
Because that's what "permanent" and "temporary" mean.
The purpose of a permanent redirect is to tell the client to always redirect to the target, so it never needs to check again.
If you want clients to always make the first request, then you need to give them a temporary redirect, so they have to check again every time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论