Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache resources in Asp.net core? [closed]

Can you please point me to an example. I want to cache some objects that will be frequently used in most of the pages on the website? I am not sure what will be the recommended way of doing it in MVC 6.

like image 637
eadam Avatar asked Feb 01 '15 23:02

eadam


1 Answers

In startup.cs:

public void ConfigureServices(IServiceCollection services)
{
  // Add other stuff
  services.AddCaching();
}

Then in the controller, add an IMemoryCache onto the constructor, e.g. for HomeController:

private IMemoryCache cache;

public HomeController(IMemoryCache cache)
{
   this.cache = cache;
}

Then we can set the cache with:

public IActionResult Index()
{
  var list = new List<string>() { "lorem" };
  this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options
  return View();
}

(With any options being set)

And read from the cache:

public IActionResult About()
{
   ViewData["Message"] = "Your application description page.";
   var list = new List<string>(); 
   if (!this.cache.TryGetValue("MyKey", out list)) // read also .Get("MyKey") would work
   {
      // go get it, and potentially cache it for next time
      list = new List<string>() { "lorem" };
      this.cache.Set("MyKey", list, new MemoryCacheEntryOptions());
   }

   // do stuff with 

   return View();
}
like image 178
NikolaiDante Avatar answered Oct 19 '22 08:10

NikolaiDante