I am trying to implement caching in ASP.NET MVC 4 using the OutputCache attribute.
Here is my controller action:
[HttpGet]
[OutputCache(Duration = CACHE_DURATION, VaryByCustom = "$LanguageCode;myParam", Location = OutputCacheLocation.Server)]
public JsonResult MyAction(string myParam)
{
}
And here is GetVaryByCustomString in Global.asax:
public override string GetVaryByCustomString(HttpContext context, string arg)
{
var pars = arg.Split(';');
if (pars.Length == 0) return string.Empty;
var res = new System.Text.StringBuilder();
foreach (var s in pars)
{
switch (s)
{
case "$LanguageCode":
var culture = CultureManager.GetCurrentCulture();
res.Append(culture.Name);
break;
default:
var par = context.Request[s];
if (par != null)
res.AppendFormat(par);
break;
}
}
return base.GetVaryByCustomString(context, res.ToString());
}
This method is always called and returns the correct value (for example, "it123").
If I call an action with only a single parameter myParam, the cache works correctly.
http://localhost:1592/MyController/MyAction?myParam=123 // called multiple times always read from cache
The problem is that when I call an action with another parameter not included in the string VaryByCustom, the controller action is called anyway, also if it should be cached, but GetVaryByCustomStringreturns the same result.
http://localhost:1592/MyController/MyAction?myParam=123&dummy=asdf // called multiple times with different 'dummy' values always calls the action
Any idea?