ASP.NET MVC OutputCache VaryByParam Objects
This is what I have:
[OutputCache(Duration = 3600, VaryByParam = "model")]
public object Hrs(ReportFilterModel model) {
var result = GetFromDatabase(model);
return result;
}
I want it to cache the new result for every other model. For now, it caches the first result, and even when the model changes, it returns the same result.
I even tried to redefine methods ToString
and GetHashCode
for ReportFilterModel. Actually I have more properties that I want to use to create unique HashCode
or String
.
public override string ToString() {
return SiteId.ToString();
}
public override int GetHashCode() {
return SiteId;
}
Any suggestions how I can get complex objects working with OutputCache
?
source to share
VaryByParam value from MSDN: A semicolon-separated list of strings that match the query string values ββfor the GET method or the parameter values ββfor the POST method.
If you want to change the output cache with all parameter values, set the attribute to an asterisk (*).
An alternative approach is to subclass the OutputCacheAttribute and reflect the user to create a VaryByParam String. Something like that:
public class OutputCacheComplex : OutputCacheAttribute
{
public OutputCacheComplex(Type type)
{
PropertyInfo[] properties = type.GetProperties();
VaryByParam = string.Join(";", properties.Select(p => p.Name).ToList());
Duration = 3600;
}
}
And in the controller:
[OutputCacheComplex(typeof (ReportFilterModel))]
For more information: How to use VaryByParam with multiple parameters?
source to share