Using Output Caching

Learn about implementing the output caching in ASP.NET Core MVC, providing examples of caching endpoints and MVC views with step-by-step instructions.

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:

Press + to interact
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:

Press + to interact
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:

Press + to interact
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:

Press + to interact
{
"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.

...