Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GetVaryByCustomString is not called

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

}
like image 313
Andrus Avatar asked Oct 17 '12 09:10

Andrus


2 Answers

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.

like image 89
Darin Dimitrov Avatar answered Oct 20 '22 10:10

Darin Dimitrov


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.

like image 33
Lara G Avatar answered Oct 20 '22 10:10

Lara G