5

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 a new result for each different model. At the moment it is caching the first result and even when the model changes, it returns the same result.

I even tried to override ToString and GetHashCode methods for ReportFilterModel. Actually I have about more properties I want to use for generating unique HashCode or String.

public override string ToString() {
    return SiteId.ToString();
}

public override int GetHashCode() {
    return SiteId;
}

Any suggestions, how can I get complex objects working with OutputCache?

Jaanus
  • 16,161
  • 49
  • 147
  • 202

1 Answers1

12

The VaryByParam value from MSDN: A semicolon-separated list of strings that correspond to query-string values for the GET method, or to parameter values for the POST method.

If you want to vary the output cache by all parameter values, set the attribute to an asterisk (*).

An alternative approach is to make a subclass of the OutputCacheAttribute and user reflection to create the VaryByParam String. Something like this:

 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 info: How do I use VaryByParam with multiple parameters?

https://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute.varybyparam(v=vs.118).aspx

Community
  • 1
  • 1
Daniel Stackenland
  • 3,149
  • 1
  • 19
  • 22
  • This does not exactly help me, how can I use complex objects there? – Jaanus May 22 '15 at 12:14
  • You cannot use your complex object but, you could set VaryByParam = "propname1;propname2;propname3" assuming it is posted or in the querystring – Daniel Stackenland May 22 '15 at 12:23
  • Made a update to my answer, is this more like what you are looking for? – Daniel Stackenland May 22 '15 at 12:48
  • Are you saying that if I define the cache property like `VaryByParam = "siteId"` , then it will use my complex object `model` property `siteId` ? – Jaanus May 22 '15 at 13:05
  • No, I say that the browser sends siteId as a querystring-value or as a formfield depending on http-method (post or get). The ASP Modelbinding uses theese values to create your model, and you can also use the same values to control the outputcaching – Daniel Stackenland May 22 '15 at 13:09