Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching JSON Data in C# MVC3

I am developing an application that presents a company's twitter feed on a Facebook application. This is a large company with lots of traffic to the FB App so I need to cache the Twitter data I receive (from the twitter API) so that I can avoid their rate limits.

In my code, I use LinqToTwitter to call the API and then I construct a string of JSON with the results. That string is then fed to the user's browser via AJAX.

The rate limit for Twitter API calls is 150 per hour, so I figure I will just place the string of JSON data I construct in a cache object and only refresh it once per minute leaving me well below the Twitter rate limit.

The problem is that I am fairly new to MVC for .NET and can't seem to use System.Web.Caching like I could do in a webforms application.

In older webforms apps I simply did something like:

            private string KeyTwitterData;

            ...

            string data = null;
            if (Cache[KeyTwitterData] == null)
            {
                var url = LinqToTwitter.Request.Url;
                data = ServiceMethods.GetConversation(url);
                Cache.Insert(KeyTwitterData, data);
            }
            else
            {
                data = (string)Cache[KeyTwitterData];
            }

Can someone please tell me how to accomplish this in MVC3?

Thanks!

Matt

like image 609
Matt Cashatt Avatar asked Sep 15 '11 07:09

Matt Cashatt


2 Answers

In ASP.NET MVC 3 if you want to cache the result of a controller action you could decorate it with the [OutputCache] attribute:

[OutputCache(Duration = 3600, Location = OutputCacheLocation.Server, VaryByParam = "none")]
public ActionResult Foo() 
{
    var model = SomeExpensiveOperationToFetchData();
    return View(model);
}

If you don't want to cache the entire output of a controller action you could use the MemoryCache class:

var data = MemoryCache.Default[KeyTwitterData];
if (data == null)
{
    data = SomeExpensiveOperationToFetchData();
    MemoryCache.Default.Add(KeyTwitterData, data, DateTime.Now.AddMinutes(5));
}

// use the data variable here
like image 144
Darin Dimitrov Avatar answered Sep 21 '22 10:09

Darin Dimitrov


Use HttpContext.Cache in your controller

string data = null;
if (HttpContext.Cache[KeyTwitterData] == null)
{
    var url = LinqToTwitter.Request.Url;
    data = ServiceMethods.GetConversation(url);
    HttpContext.Cache.Insert(KeyTwitterData, data);
}
else
{
    data = (string)HttpContext.Cache[KeyTwitterData];
}
like image 42
Dave Walker Avatar answered Sep 20 '22 10:09

Dave Walker