How to use caching in ASP.NET Web API?

Unfortunately, caching is not built into ASP.NET Web API.

Check this out to get you on track: http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/

An updated resource here: https://github.com/filipw/AspNetWebApi-OutputCache

EDIT: As of 2020-02-03, even though this answer is quite old, it's still valid.

Both of the URL's above lead to the same project, ASP.NET Web API CacheOutput by Filip W


Add a reference to System.Runtime.Caching in your project. Add a helper class :

using System;
using System.Runtime.Caching;


public static class MemoryCacher
{
    public static object GetValue(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Get(key);
    }

    public static bool Add(string key, object value, DateTimeOffset absExpiration)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        return memoryCache.Add(key, value, absExpiration);
    }

    public static  void Delete(string key)
    {
        MemoryCache memoryCache = MemoryCache.Default;
        if (memoryCache.Contains(key))
        {
            memoryCache.Remove(key);
        }
    }
}

Then from your code get or set objects in the cache :

list = (List <ChapterEx>)MemoryCacher.GetValue("CacheItem1");

and

MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));