Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅为匿名用户缓存ASP.NET页_Asp.net_Caching_Forms Authentication - Fatal编程技术网

仅为匿名用户缓存ASP.NET页

仅为匿名用户缓存ASP.NET页,asp.net,caching,forms-authentication,Asp.net,Caching,Forms Authentication,是否有一种简单的方法可以仅为匿名用户缓存ASP.NET整个页面(使用表单身份验证) 上下文:我正在制作一个网站,其中显示给匿名用户的页面大部分是完全静态的,但为登录用户显示的相同页面却不是 当然,我可以通过代码隐藏手动完成这项工作,但我认为可能有更好/更简单/更快的方法。您可以使用VaryByCustom,并使用类似username的键。我使用的是asp.net MVC,所以我在我的控制器中实现了这一点 if (User.Identity.IsAuthenticated) { Respo

是否有一种简单的方法可以仅为匿名用户缓存ASP.NET整个页面(使用表单身份验证)

上下文:我正在制作一个网站,其中显示给匿名用户的页面大部分是完全静态的,但为登录用户显示的相同页面却不是


当然,我可以通过代码隐藏手动完成这项工作,但我认为可能有更好/更简单/更快的方法。

您可以使用
VaryByCustom
,并使用类似
username
的键。

我使用的是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函数在未经身份验证时返回“anonymous”,或者在可用时返回用户名。

没有任何东西可以阻止您使用所需的行为扩展现有属性

例如:

public class AnonymousOutputCacheAttribute : OutputCacheAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    {
       if(filterContext.HttpContext.User.Identity.IsAuthenticated)
          return;

        base.OnActionExecuting(filterContext);
    }  
}  

尚未对此进行测试,但我看不出这不起作用的原因。

问题在于它也会缓存显示给登录用户的页面。在我的例子中,这些页面已经部分缓存,而一些部分根本无法缓存(即使对于同一个用户)。当然,如果用户登录,我可以将VaryByCustom key设置为一个随机值,但这会带来巨大的性能问题。您有没有解决过这个问题?我们有一个类似的需求,varyByCustom不是解决方案。目前我使用代码隐藏解决方案,在这里我可以轻松决定是否要缓存页面。如果用户未登录,我将缓存。如果用户已登录,则整个页面的缓存将被禁用(而只缓存“静态”部分)。在我收到下面的答案后,我搜索了一个没有代码隐藏的解决方案,但没有发现任何有用的东西。毕竟,代码隐藏解决方案也是非常明确的,并且与纯ASP.NET解决方案相比没有重大缺点。您能分享您的代码隐藏解决方案吗?如何像那样控制缓存?在代码中,如果默认情况下缓存了页面,请添加如下内容:if(User.Identity.IsAuthenticated){Response.cache.SetCacheability(HttpCacheability.NoCache);Response.cache.SetExpires(DateTime.Now.AddMinutes(-1));Response.cache.SetNoStore();}或者,如果用户未登录,可以在代码中设置缓存,并避免在ASP.NET端设置任何内容。(很抱歉代码没有缩进。找不到如何在注释中换行…@MainMa您看到这个答案了吗?