ASP NET MVC OutputCache VaryByParam complex objects
Asked Answered
I

1

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?

Intertwine answered 22/5, 2015 at 11:20 Comment(0)
A
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

Assembled answered 22/5, 2015 at 11:42 Comment(5)
This does not exactly help me, how can I use complex objects there?Intertwine
You cannot use your complex object but, you could set VaryByParam = "propname1;propname2;propname3" assuming it is posted or in the querystringAssembled
Made a update to my answer, is this more like what you are looking for?Assembled
Are you saying that if I define the cache property like VaryByParam = "siteId" , then it will use my complex object model property siteId ?Intertwine
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 outputcachingAssembled

© 2022 - 2024 — McMap. All rights reserved.