Using app.UseOutputCache()
in ASP.NET Core (Razor Pages + API + Conditional Caching)
Output Caching is a feature introduced in .NET 7 that helps improve performance by caching full HTTP responses in memory and serving them directly for repeated requests.
What is Output Caching?
Output caching stores the full server-generated response so that if the same request comes in again, the server can return the cached response without recomputing the result.
Benefits:
- Faster response time
- Reduced server load
- Easy to configure per endpoint or via policy
How to Enable Output Caching
In Program.cs
, add the caching service and middleware:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddOutputCache(); // Register output caching builder.Services.AddRazorPages(); builder.Services.AddControllers(); builder.Services.AddOutputCache(options => { options.AddPolicy("TimePolicy", policy => { policy.Expire(TimeSpan.FromSeconds(20)) .SetVaryByQuery("noCache"); }); }); var app = builder.Build(); app.UseRouting(); app.UseOutputCache(); // Enable caching middleware app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); });
📄 Razor Page Example
Pages/Index.cshtml
:
@page @model IndexModel <h1>Welcome</h1> <p>This page is not cached by default.</p>
Pages/Index.cshtml.cs
:
using Microsoft.AspNetCore.Mvc.RazorPages; public class IndexModel : PageModel { public void OnGet() { } }
API Example with Conditional Cache
Here’s an API that returns the current server time and supports bypassing cache via a query parameter:
[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 }); } }
Output Cache vs Response Cache
Feature | Output Cache | Response Cache |
---|---|---|
Location | Server (in-memory) | Client/CDN (via headers) |
Setup | Middleware | HTTP headers |
Logic Control | Fully programmable | Limited |
Best for | APIs, dynamic content | Static/public responses |
Download Full Sample Project
The complete ready-to-push-to-GitHub sample project is available here:
👉 Download OutputCacheSample (GitHub-Ready ZIP)
Includes:
- Razor Page
- API with conditional cache
- OutputCache policy config
Final Notes
Output caching is simple to add but highly effective in boosting web application performance. You can easily customize its behavior with route, query, or header parameters.
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
🏷 Tags:
aspnetcore
, dotnet
, caching
, performance
Top comments (0)