Is it possible to use ASP.NET application caching

2019-02-25 06:30发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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

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



回答4:

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.