allan
allan

Reputation: 276

How do I configure OutputCache page attribute for varying querystring values?

Assuming I have a page request which goes like

http://localhost/accounting/products?id=234

and sometimes it goes like:

http://localhost/accounting/products?id=152

Since product items does not change frequently, I want each pages for a particular product ID to be cached for an hour.

So for the first request the page will be cached for product id = 234 and succeeding request for the product id =234 within an hour, will be retrieved from the cache. The next request after 1 hour has elapsed for product id =234, a new page will be retrieved from the server not from the cache. And so on.

How do I go about this?

Upvotes: 4

Views: 1283

Answers (3)

Chris Moschini
Chris Moschini

Reputation: 37947

Just for reference, if you've got multiple params it needs to cache by, separate them with semicolons:

// Cache 4 hours, by id and latlng
[OutputCache(Duration=60*60*4, VaryByParam="id;lat;lng")]
public async Task<ViewResult> Item(int id, double lat, double lng) . . .

Upvotes: 0

Ofer Zelig
Ofer Zelig

Reputation: 17480

Check out VaryByParam.

For example:

<%@ OutputCache Duration="3600" VaryByParam="id" %>

Note: The correct way to do it specifically in MVC (as opposed to Web Forms) is by attributing an action, as Oenning demonstrated.

Upvotes: 6

goenning
goenning

Reputation: 6654

Ofer Zelig's answer is right, but as you are using MVC, the correct location to add the OutputCache configuration is in the action.

[OutputCache(Duration=3600, VaryByParam="id")]
public ActionResult Products(int id)
{
    //
    return View();
}

Upvotes: 6

Related Questions