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

?

+3


source to share


1 answer


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?

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

+10


source







All Articles