简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM