I want to cache return data from an action. I use the OutPutCacheAttribute
for this purpose. Here is my client code:
$(document).ready(function() {
$.get('@Url.Action("GetMenu", "Home")', null,
function(data) {
parseMenu(data);
});
}
And here is my server code:
[HttpGet]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.Server)]
public ContentResult GetMenu()
{
string jsonText = GetData(); //some code
return new ContentResult
{
Content = jsonText,
ContentType = "text/json"
};
}
As you can see I use OutputCacheAttribute
for caching server response. But it does not work. Every time I load the page the action Home/GetMenu
is called. And it is called even if I type in browser's address bar directly 'localhost/Home/GetMenu'. Where am I was mistaken?
UPD I created the second action to test this attribute without debugging. Here is its code:
[HttpGet]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "none")]
public JsonResult GetJson()
{
return Json(new
{
random = new Random().Next(100)
},
JsonRequestBehavior.AllowGet);
}
I supposed if OutputCache attribute works properly (and I use it properly) then action is called once and I get the same response every time. But if not then I get the different responses every time because every time random number is genereted.
And when I called this action some times I have always received different respnses, such as {"random":36}
, {"random":84}
and so on
It allows varying the cached output by GET query string or form POST parameters. For instance, you can vary the user-control output to the cache by specifying the user-control name along with either a query string or a form POST parameter. For more information, see Caching Multiple Versions of User Control Output.
The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.
ANSWER: The VaryByParam attribute determines which versions of the page output are actually cached.
In its default implementation, output cache is process-bound and stored in-memory. As a result, if you do something like stop and start debugging, you've destroyed anything you previously cached. Actually, more accurately, you've killed the process and started a new process, and since the cache is process-bound it went away with the old process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With