THX-1138
THX-1138

Reputation: 21730

Enable client side caching for "dynamic" content (asp.net mvc 3.0)

Context: ASP.NET MVC 3.0, .NET 4.0, C#, IIS 7

I have a long list of names (of game realms/servers). The realms are stored in a database.
I have an Action that returns the list as a JSON code.

I reference the list in my .aspx as following:

<script type="text/javascript" src='<%= Url.Action("Realms", "Data") %>'></script>

Here is an abbreviated action itself:

    public ActionResult Realms() {
        var realms = Data.GetRealms(...);
        var json = JsonSerialize(realms);
        return Content("realms = {0};".With(json), "text/javascript", Encoding.UTF8);
    }

This list changes very seldom (once a month).

Question: how can I cause this .js file be cached client side?

Details My problem is that this "file" is being downloaded on each page refresh and accounts for 20% of the traffic.

Upvotes: 2

Views: 4928

Answers (2)

CedricB
CedricB

Reputation: 1167

If you must cache on the client you have some options...

There are probably more options but these are the ones that come to mind.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

how can I cause this .js file be cached client side?

It would be more reliable to cache it on the server by decorating the action with the [OutputCache] attribute. If you want to cache it on the client you could configure the cache cache location on the client when using this attribute which will send the proper Cache-Control HTTP response header:

[OutputCache(Location = OutputCacheLocation.Client, Duration = 20)]
public ActionResult Realms()
{
    ...
}

Upvotes: 4

Related Questions