Course contentsShow
← C#
Lesson 1311 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Performance Optimization in Rendering

Apply partial view caching and output caching to reduce server workload.

In this lesson, you will learn how to drastically reduce server load by caching rendered HTML fragments using Partial View Caching and Output Caching.

When building complex Razor pages, your server often performs heavy database lookups or complex business logic just to render small, static components—like a navigation menu or a site footer. Instead of re-computing these on every request, we can cache the rendered output.

Partial View Caching

While Razor doesn't provide a native "CachePartial" helper, the standard approach is to wrap the logic inside your View or Partial View using the <cache> Tag Helper. This helper stores the rendered HTML in memory, serving it directly to subsequent users without hitting the controller or data access layer again.

<cache expires-after="@TimeSpan.FromMinutes(10)">
    <partial name="_HeavyFooter" model="Model.FooterData" />
</cache>

In this example, the partial view _HeavyFooter is rendered once. For the next ten minutes, any request reaching this page will receive the pre-rendered HTML block from the cache, bypassing the logic needed to build it.

Output Caching

Output caching is a higher-level strategy where you cache the result of an entire action method. In modern ASP.NET Core, you can apply this via middleware. When configured, the server checks if it has a stored version of the requested page before executing your controller logic.

If you have a dashboard that updates only every hour, you can drastically reduce your server workload by configuring the cache policy in your Program.cs:

builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(builder => builder.Expire(TimeSpan.FromHours(1)));
});

By combining these strategies, you ensure that the Razor engine only works when necessary. Use Partial View Caching for reusable, semi-static components like widgets or sidebars, and use Output Caching for complete pages that don’t require real-time updates for every visitor. This moves your application from "computing per request" to "serving pre-rendered content," which is the single most effective way to improve response times and handle higher traffic spikes.

Key Takeaway: By using the <cache> tag helper for partial views and Output Caching for controller actions, you prevent redundant server-side processing and significantly accelerate your application's rendering performance.