Is it possible to use ASP.NET application caching in web API?

后端 未结 4 1493
北荒
北荒 2021-01-19 23:15

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 th

相关标签:
4条回答
  • 2021-01-19 23:40

    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.

    0 讨论(0)
  • 2021-01-19 23:42

    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.

    0 讨论(0)
  • 2021-01-19 23:52

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

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

    0 讨论(0)
  • 2021-01-20 00:00

    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.

    0 讨论(0)
提交回复
热议问题