如何关闭输出缓存关闭在ASP.NET MVC中身份验证的用户? [英] How to turn output caching off for authenticated users in ASP.NET MVC?

查看:115
本文介绍了如何关闭输出缓存关闭在ASP.NET MVC中身份验证的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序。我不过需要缓存一些网页的作为非认证用户。

I have an ASP.NET MVC application. I need to cache some pages however only for non-authenticated users.

我试图用 VaryByCustom是=用户具有以下 GetVaryByCustomString 实施

public override string GetVaryByCustomString(HttpContext context, string custom)
{
  if (custom == "user")
  {
      if (context.User.Identity.IsAuthenticated)
      {
        return context.User.Identity.Name;
      }
      else
      {
        return "";
      }
  }  

  return base.GetVaryByCustomString(context, custom);
}

然而,这不正是我所需要的,因为页面仍缓存。唯一不同的是,现在被缓存分别为每个用户。

However this isn't exactly what I need because pages are still cached. Only difference is that now is cached for each user separately.

一个可行的办法是返回 Guid.NewGuid()每次当用户进行身份验证的时间,但它看起来像一个巨大的资源浪费在我身上。

One possible solution is to return Guid.NewGuid() each time when user is Authenticated, but it looks like a huge waste of resources to me.

那么,你有什么秘诀给我吗?

So do you have any tips for me?

推荐答案

因此​​,这里是我做了什么:

So here is what I done:

public class NonAuthenticatedOnlyCacheAttribute : OutputCacheAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
      var httpContext = filterContext.HttpContext;

      if (httpContext.User.Identity.IsAuthenticated)
      {
        // it's crucial not to cache Authenticated content
        Location = OutputCacheLocation.None;
      }

      // this smells a little but it works
      httpContext.Response.Cache.AddValidationCallback(IgnoreAuthenticated, null);

      base.OnResultExecuting(filterContext);
    }

    // This method is called each time when cached page is going to be
    // served and ensures that cache is ignored for authenticated users.
    private void IgnoreAuthenticated(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
      if (context.User.Identity.IsAuthenticated)            
        validationStatus = HttpValidationStatus.IgnoreThisRequest;          
      else          
        validationStatus = HttpValidationStatus.Valid;          
    }
}

非常感谢克雷格斯顿茨谁向我指出方向是否正确,他们的回答是我无意中downvoted。

Many thanks to Craig Stuntz who pointed me to correct direction and whose answer I unwittingly downvoted.

这篇关于如何关闭输出缓存关闭在ASP.NET MVC中身份验证的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆