How to cache resources in Asp.net core?

I think currently there no such like OutputCache attribute available that avaiable in ASP.net MVC 5.

Mostly attribute is just shortcut and it will indirectly use Cache provider ASP.net.

Same thing available in ASP.net 5 vnext. https://github.com/aspnet/Caching

Here different Cache mechanism available and you can use Memory Cache and create your own attribute.

Hope this help you.


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();
}

The recommended way to do it in ASP.NET Core is to use the IMemoryCache. You can retrieve it via DI. For instance, the CacheTagHelper utilizes it.

Hopefully that should give you enough info to start caching all of your objects :)