When it comes to memory caching, you might immediately think of Httpruntime.cache, which is located under the System.Web namespace, but system.web no longer exists in ASP. Just talk about it today. How to use memory caching in ASP. We generally have access to the cache of data that is often accessed but not often changed, which can significantly improve the performance of your application. About MemoryCache on GitHub address: https://github.com/aspnet/Caching Total 4 items
The first item is the cache abstraction, the other three are different types Memory,redis,sqserver
First, you need to register the cache service in Configureservices
public void Configureservices (iservicecollection services) { services. Addmemorycache (); Services. Addmvc ();}
Get the IMemoryCache instance from the home Controller's constructor in the following code
public class homecontroller:controller{ private IMemoryCache _cache; Public HomeController (IMemoryCache memorycache) { _cache = MemoryCache; }}
About the use of the cache is commonly used is set Get Remove, some people like to encapsulate the code in a separate class library, I think it is not necessary, it can be directly used in our web project directly, and the Imemory provides the extension method is the best package
Set the cache set
_cache. Set ("Key", "value");
Get Cache get
var result = _cache. Getorcreate ("MyKey", (entry) =>{ entry. Absoluteexpirationrelativetonow = Timespan.fromseconds (+); return DateTime.Now.ToString ();});
Remove Cache Remove
_cache. Remove ("key");
Using MemoryCache in ASP. NET Core 2.0