cachingasp.net-core-mvc.net-8.0outputcache

Partial output caching aka. donut caching in .NET 8


I was wondering if there is a best-practice to implement something analog to outputcaching that still allows us to generate a small part of the response server-side, despite the rest being outputcached? We use ASP.NET Core MVC Razor pages to render responses server side.

There used to be a nuget called MvcDonutCaching that allowed us to do that in .NET 4.8 era but that's been deprecated.

Specifically, we need to integrate an ad platform into our solution but this ad platform is server-to-server, so cannot be embedded solely on the client-side. We obviously don't want to give up the output caching we heavily use and rely on today to offload backend processing at peaks.


Solution

  • You could try following sample to do partial cache in asp.net core

    Index.cshtml

    @using Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    
    <!-- Cached Section -->
    <cache vary-by-route="true" expires-after="TimeSpan.FromMinutes(1)">
        <p>Cached Time: @DateTime.Now.ToString("HH:mm:ss")</p>
    </cache>
    
    <!-- Dynamic Section -->
    <p>Non-Cached Time: @DateTime.Now.ToString("HH:mm:ss")</p>
    

    Note: when you refresh the page, you will find the cached section time doesn't change ,because they are from cached resource.
    As Rok suggested. distributed-cache is even better option.