9

输出缓存是在 ASP.NET MVC2 中使用下面的代码实现的。

GetVaryByCustomString方法未调用:将断点置于其第一行并运行应用程序显示未到达断点。到达控制器 Index() 中的断点。

如何VaryByCustom 在 ASP.NET MVC2 中使用?

控制器:

        [OutputCache(VaryByCustom = "user")]
        public ActionResult Index(string _entity, string id)
        {
...

全球.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    public  override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg == "user")
        {
            HttpCookie cookie = context.Request.Cookies["Company"];
            if (cookie != null)
                return Thread.CurrentPrincipal.Identity.Name + "," + cookie.Value;
            return Thread.CurrentPrincipal.Identity.Name;
        }
        return base.GetVaryByCustomString(context, arg);
    }

}
4

3 回答 3

10

您的 OutputCache 定义是错误的。您必须指定Duration

[OutputCache(VaryByCustom = "user", Duration = 50)]
public ActionResult Index(string _entity, string id)

GetVaryByCustomString现在将调用您覆盖的方法。也不要忘记GetVaryByCustomString只有在控制器操作完成执行后才会调用该方法。

于 2012-10-17T09:52:06.213 回答
2

我只想提两个其他原因

如果项目中有任何[NoCache]属性,GetVaryByCustomString将不会触发。

如果你把

Location = OutputCacheLocation.Client, 

GetVaryByCustomString不会触发。

于 2014-12-23T12:42:54.697 回答
1

我最近参与的一个项目有一个全局过滤器,阻止输出缓存工作:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new NoCacheResponseAttribute());
    }
}

public class NoCacheResponseAttribute : BaseActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
       var response = filterContext.RequestContext.HttpContext.Response;
       response.Cache.SetCacheability(HttpCacheability.NoCache);
       response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
       response.Cache.SetNoStore();
    }
}

在注释添加过滤器的行后,输出缓存开始按预期工作。

于 2017-01-25T19:19:21.763 回答