Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET MVC OutputCache VaryByParam complex 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 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?

like image 522
Jaanus Avatar asked May 22 '15 11:05

Jaanus


1 Answers

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

like image 122
Daniel Stackenland Avatar answered Nov 01 '22 20:11

Daniel Stackenland