app.UseOutputCache() in ASP.NET Core

Morteza JangjooMorteza Jangjoo
3 min read

Output Caching is a new and powerful feature in ASP.NET Core introduced in .NET 7 that allows developers to cache full HTTP responses in memory and serve them for subsequent requests — boosting performance and reducing unnecessary processing.


What is Output Caching?

Output caching stores the full response generated by your application (such as a Razor Page or API controller response) in server memory, so that subsequent identical requests are served from the cache instead of being regenerated.

This is especially useful for:

  • Expensive computations (e.g., report generation)

  • Frequently requested static or semi-dynamic content

  • Improving API response times


How to Enable Output Caching

Add OutputCache service and middleware in your Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Enable Output Caching
builder.Services.AddOutputCache();

var app = builder.Build();

app.UseRouting();

// Enable the middleware
app.UseOutputCache();

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
});

Basic Example: Razor Page

Let’s create a simple Razor Page (/Pages/Index.cshtml) that shows a welcome message:

@page
@model IndexModel
<h1>Welcome</h1>
<p>This page is not cached by default.</p>

And its code-behind (Index.cshtml.cs):

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.OutputCaching;

public class IndexModel : PageModel
{
    public void OnGet()
    {
        // Normal page load
    }
}

This page does not have caching by default, but you can apply policies or filters later.


API Example with Conditional Caching

We’ll create an API that returns the current time, with optional noCache query support.

[ApiController]
[Route("api/[controller]")]
public class TimeController : ControllerBase
{
    [HttpGet("now")]
    [OutputCache(PolicyName = "TimePolicy")]
    public IActionResult GetTime([FromQuery] bool noCache = false)
    {
        if (noCache)
        {
            HttpContext.Response.Headers["Cache-Control"] = "no-store";
        }

        return Ok(new { Time = DateTime.Now });
    }
}

Then, define the policy in Program.cs:

builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("TimePolicy", policy =>
    {
        policy.Expire(TimeSpan.FromSeconds(20))
              .SetVaryByQuery("noCache");
    });
});

Now, accessing /api/time/now will return a cached response for 20 seconds — unless you use ?noCache=true to bypass it.


Output Cache vs Response Cache

FeatureOutput CacheResponse Cache
LocationServer memoryBrowser / Proxy
ConfigurationMiddleware-basedHeader-based
Bypass LogicFully controllable in server logicLimited
Suitable ForDynamic APIs, server-side renderingStatic content

Benefits of UseOutputCache()

  • Lightning-fast response times for repeated requests

  • Less pressure on your application logic or database

  • Fine-grained cache control using query strings, headers, routes, etc.

  • Easy to implement and extend


📦 Download Full Project

I’ve created a full ready-to-run project with:

  • Razor Page example

  • API with cache bypass logic

  • Output cache policy configuration

👉 Download OutputCacheSample (GitHub Ready)


💬 Final Thoughts

Output caching is a great feature for improving app performance without the complexity of external caching layers. With just a few lines of code, you can serve responses faster and keep your backend scalable.

I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”


0
Subscribe to my newsletter

Read articles from Morteza Jangjoo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Morteza Jangjoo
Morteza Jangjoo