Why GetVaryByCustomString is not called

The output cache is implemented in ASP.NET MVC2 using the code below.

GetVaryByCustomString method is not called: placing a breakpoint on the first line and the running application shows that the breakpoint has not been reached. A breakpoint has been reached in the Index () controller.

How to use VaryByCustom in ASP.NET MVC2?

Controller:

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

Global.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); } } 
+7
source share
3 answers

The definition of OutputCache is incorrect. You must specify Duration :

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

Your overridden GetVaryByCustomString method will now be called. Also, do not forget that the GetVaryByCustomString method will only be called after the controller completes.

+7
source

I just want to mention 2 more reasons

If the project has any [NoCache] attribute, GetVaryByCustomString will not fire.

If you put

 Location = OutputCacheLocation.Client, 

GetVaryByCustomString will not fire.

+1
source

The project I was working on recently had a global filter to prevent output caching from working:

 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(); } } 

After commenting out the line that adds the filter, the output caching started working as expected.

0
source

All Articles