Why GetVaryByCustomString is not called
Asked Answered
P

3

9

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

GetVaryByCustomString method is not called: placing breakpoint to its first line and running application shows that breakpoint is not reached. Breakpoint in controller Index() is reached.

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

}
Phobia answered 17/10, 2012 at 9:47 Comment(0)
C
10

Your OutputCache definition is wrong. You must specify the Duration:

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

Now your overridden GetVaryByCustomString method will be called. Also don't forget that the GetVaryByCustomString method will be called only after the controller action has finished executing.

Cassity answered 17/10, 2012 at 9:52 Comment(1)
Thank you. After adding this Vary:* header is sent to browser and this disables browser cache. How to enable browser cache with VaryByCustom?Phobia
C
2

I just want to mention 2 other causes

If there is any [NoCache] attribute in project, GetVaryByCustomString will not fire.

If you put

Location = OutputCacheLocation.Client, 

GetVaryByCustomString will not fire.

Coss answered 23/12, 2014 at 12:42 Comment(0)
P
1

A project that I worked on recently had a global filter preventing 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 the line which adds the filter, output caching started working as expected.

Polivy answered 25/1, 2017 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.