有没有一种简单的方法可以只为匿名用户缓存整个ASP.NET页面(使用表单身份验证)?
背景:我正在制作一个网站,其中显示给匿名用户的页面大多是完全静态的,但为登录用户显示的相同页面却不是。
当然,我可以通过后台代码手动完成此操作,但我认为可能有更好/更容易/更快的方法。
发布于 2010-01-18 00:29:57
您可以使用VaryByCustom,并使用像username这样的密钥。
发布于 2011-09-17 02:04:33
我使用的是asp.net MVC,所以我在我的控制器中做了这件事
if (User.Identity.IsAuthenticated) {
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddMinutes(-1));
Response.Cache.SetNoStore();
Response.Cache.SetNoServerCaching();
}
else {
Response.Cache.VaryByParams["id"] = true; // this is a details page
Response.Cache.SetVaryByCustom("username"); // see global.asax.cs GetVaryByCustomString()
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
}我之所以这样做(而不是以声明的方式),是因为我还需要通过配置打开和关闭它的能力(这里没有显示,但在配置变量的if中有一个额外的检查)。
您仍然需要vary by username,否则当登录的用户出现时,您将无法执行此代码。我的GetVaryByCustomString函数在未通过身份验证时返回“匿名”,或在用户名可用时返回用户名。
发布于 2015-05-02 05:25:19
没有什么可以阻止您使用所需的行为扩展现有的属性。
例如:
public class AnonymousOutputCacheAttribute : OutputCacheAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(filterContext.HttpContext.User.Identity.IsAuthenticated)
return;
base.OnActionExecuting(filterContext);
}
} 我还没有测试过这个,但我看不出为什么它不能工作。
https://stackoverflow.com/questions/2081638
复制相似问题