Pupkin
Pupkin

Reputation: 1111

OutputCache doesn't work

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

Upvotes: 10

Views: 7719

Answers (3)

Torbjörn Hansson
Torbjörn Hansson

Reputation: 19423

Have you checked web.config that it isn't disabled?

https://msdn.microsoft.com/en-us/library/ms228124(v=vs.100).aspx

<caching>
    <outputCache enableOutputCache="false">
    </outputCache>
</caching>

Upvotes: 1

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Please try this

  [OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient,VaryByParam = "none")]

If not working Please try :

        [HttpGet]
    [OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "none")]
    public JsonResult GetJson()
    {
        return Json(new{message = "Record created successfully!!!"},JsonRequestBehavior.AllowGet);
    }

N.B. : more information about Outputcache

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239440

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.

Upvotes: 1

Related Questions