Written by Mark Pringle | Last Updated on Friday, December 02, 2022

ASP.NET Core ASP.NET Version: 6.0 Tutorial Articles

Output caching is not available in asp.net core 6. It is available in ASP.NET Core 7.0 and later, but that doesn’t help if you use Core 6. So, how do we perform server-side caching? 

There is a workaround so that you can use output caching in your ASP.NET Core 6.0 MVC web applications. The first thing that you need to do is to use the NuGet Package Manager to install WebEssentials.AspNetCore.OutputCaching. WebEssentials.AspNetCore.OutputCaching is an ASP.NET Core middleware providing pure server-side output caching through a simple-to-use API.

WebEssentials.AspNetCore.OutputCaching

After this middleware package is installed in your project, you need to make a couple of additions to your Program.cs file. Add services.AddOutputCaching() and app.UseOutputCaching(). 

//WebEssentials.AspNetCore.OutputCaching
builder.Services.AddOutputCaching();
//WebEssentials.AspNetCore.OutputCaching
app.UseOutputCaching();

Now, your website supports output caching.

Next, you can add the OutputCache directive to the action method within the controller.

// GET: Home Page Articles
[OutputCache(Duration = 43200)]
public async Task<IActionResult> Index()
{
     var results = await _context.ArticleSelect.FromSqlInterpolated($"exec dbo.ArticlesHomePage").ToListAsync();
     return View(results);
}

The duration parameter will tell the framework how long it takes to cache the page, and it needs to be input in seconds. In the above example, the data is cached for 43200 seconds or 12 hours; that’s (60 seconds x 60 minutes x 12 hours).

As of this writing, I have yet to figure out how to disable caching for content containing authenticated clients' information when applying the OutputCache to an action method. This approach caches the entire page, including authentication and authorization areas. That's not good. However, if you want to cache only the data, use the OutputCache directive on the model or class, like below.

namespace LearnASPNET.Models
{
    [OutputCache(Profile = "defaultlong")]
    public partial class ArticleSelect
    {
        [Key]
        public int Id { get; set; }
        public string ContributorId { get; set; } = null!;
        .......
    }
}

Notice that I did not explicitly set the cache length above in seconds as I did in the controller example. Instead, I used a default profile set up in the Program.cs file.

//WebEssentials.AspNetCore.OutputCaching
builder.Services.AddOutputCaching(options =>
{
    options.Profiles["defaultlong"] = new OutputCacheProfile
    {
        Duration = 43200
    };
});

Happy coding!

Be sure to check out the WebEssentials.AspNetCore.OutputCaching GitHub resources.