4

For example, in a ASP.NET page you would do something like

Cache.Add({...}) and access it via Cache["key"]. In this context, Cache is the System.Web.Caching.Cache object.

Is there anyway to do this type of ASP.NET application level caching in web API controllers?

4 Answers 4

11

Take a look at the MemoryCache class. From its MSDN documentation:

The MemoryCache class is similar to the ASP.NET Cache class. The MemoryCache class has many properties and methods for accessing the cache that will be familiar to you if you have used the ASP.NET Cache class. The main differences between the Cache and MemoryCache classes are that the MemoryCache class has been changed to make it usable by .NET Framework applications that are not ASP.NET applications.

You can create a new instance of a MemoryCache yourself, or you can use the default AppDomain-wide instance via the MemoryCache.Default static property.

Edit: You'll need to add a reference to System.Runtime.Caching.dll if you wish to use this type.

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure why this doesn't have more upvotes (and should be the accepted answer). This behaves much like the ASP.NET cache and still allows for portability without being tied to ASP.NET/IIS
10

If you are web hosting, why not?

var context = HttpContext.Current;

if (context != null)
{
    if (context.Cache["g"] == null)
    {
        context.Cache["g"] = 9.81;
    }
}

But you are adding a dependency on ASP.NET by doing so. Even though ASP.NET Web API has ASP.NET in the name, the Web API is host-agnostic. That is, ASP.NET/IIS is not the only hosting option; the Web API can be self-hosted as well. Something for you to consider before going down that route.

Comments

1

You need to type

HttpContext.Current.Cache

to access the instance. There is no Cache property declared at the Controller level, like on a Page.

Note that the context that hosts the API will need to support caching.

Comments

0

If you are referring to Output caching in ASP.NET Web API. Take a look at this project,

https://github.com/filipw/AspNetWebApi-OutputCache

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.