Search⌘ K
AI Features

Using Output Caching

Explore how to enhance the performance of ASP.NET Core MVC applications by using output caching. Learn to configure caching middleware, cache endpoints, and cache MVC views to reduce server load and improve response times. This lesson guides you through practical steps to implement output caching, including setting expiration times, monitoring cache behavior, and handling dynamic content efficiently.

In some ways, output caching is similar to response caching. Output caching can store dynamically generated responses on the server so that they do not have to be regenerated again for another request. This can improve performance.

Output caching endpoints

Let’s see it in action with a really simple example of applying output caching to some endpoints to make sure it is working properly:

Step 1: In the Northwind.Mvc project, in Program.cs, add statements after the call to AddNorthwindContext to add the output cache middleware and override the default expiration timespan to make it only 10 seconds, as shown highlighted in the following code:

C#
builder.Services.AddNorthwindContext();
builder.Services.AddOutputCache(options =>
{
options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10);
});

Note: The default expiration time span is one minute. Think carefully about what the duration should be.

Step 2: In Program.cs, before the call to map controllers, add statements to use the output cache, as shown in the following code:

C#
app.UseOutputCache();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

Step 3: In Program.cs, add statements after the call to map Razor Pages to create two simple endpoints that respond with plain text, one that is not cached and one that uses the output cache, as shown highlighted in the following code:

C#
app.MapRazorPages();
app.MapGet("/notcached", () => DateTime.Now.ToString());
app.MapGet("/cached", () => DateTime.Now.ToString()).CacheOutput();

Step 4: In appsettings.Development.json, add a log level of Information for the output caching middleware, as shown in the following configuration:

Javascript (babel-node)
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.OutputCaching": "Information"
}
}
}

Step 5: Start the Northwind.Mvc website project and arrange the browser window and command prompt or terminal window so we can see both. ...