DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
FREEDOM251

Freedom251 › Blog › .NET Web API

How to Enable ASP.NET Core Output Caching and Speed Up .NET Web APIs

By Freedom251 Team · · 10 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ASP.NET Core output caching can make repeat Web API requests substantially cheaper and faster by storing a complete HTTP response and serving it without running the endpoint again. To use it safely, register the output-cache services, place the middleware after authentication and authorization, and opt only suitable GET or HEAD endpoints into a policy. Then design cache keys around every input that changes the response, choose an explicit freshness window, and provide tag-based invalidation for writes.

The framework does not publish a universal latency or throughput percentage because gains depend on endpoint cost, hit rate, storage, payload size, and deployment topology. Measure those values in your own environment rather than promising a fixed improvement.

As an Amazon Associate I earn from qualifying purchases.

What ASP.NET Core output caching does

Output caching stores the generated HTTP response for an endpoint: status code, headers, and body. When a later request matches the cache key and the entry is still valid, ASP.NET Core returns that stored response instead of invoking the handler, controller action, view, database query, or downstream service again. This is different from caching an individual database query or object inside application code; the cache sits at the HTTP response boundary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Microsoft’s middleware supports Minimal APIs, controller-based Web APIs, MVC, and Razor Pages. Registration makes the feature available, but an endpoint still needs an opt-in policy or attribute before a response is cached.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Where output caching helps most

  • Public GET endpoints that return the same representation to many callers.
  • Expensive aggregations, catalog pages, documentation pages, and read-heavy reports.
  • Responses backed by slow or rate-limited downstream APIs where a short period of reuse is acceptable.
  • Endpoints whose freshness requirement can be expressed as a clear time-to-live or an explicit purge event.

Where it is risky

  • User-specific, tenant-specific, or permission-sensitive data unless the cache key deliberately varies by every relevant identity or claim.
  • Responses that change faster than the selected expiration period.
  • Operations with side effects, including POST, PUT, PATCH, and DELETE; these are not cached by the default rules.
  • Responses whose representation depends on an unaccounted-for header, route value, host, query parameter, or custom context.

Enable output caching in a .NET application

The minimum setup has three parts: register services, add middleware, and opt an endpoint into caching.

  1. Register the service. Add AddOutputCache while configuring services.
  2. Add middleware. Call UseOutputCache in the request pipeline.
  3. Opt in the endpoint. Use CacheOutput() for a Minimal API route, a named policy, or the [OutputCache] attribute on a controller action.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOutputCache();

var app = builder.Build();

app.UseOutputCache();

app.MapGet("/cached", () => Results.Ok(new { message = "cached response" }))
   .CacheOutput();

app.Run();

Calling only AddOutputCache and UseOutputCache does not cache every route. The endpoint must be configured for output caching. This explicit opt-in prevents an unexpected policy from applying to sensitive or highly dynamic responses.

Pipeline order with authentication and authorization

In an application that uses authentication or authorization, place output caching after both middleware components:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseOutputCache();

app.MapControllers();

This ordering ensures the request reaches authentication and authorization before a cached representation can be served. A cached response must never bypass an authorization decision. Keep user-specific endpoints excluded unless you have designed and tested identity-aware variation.

Choose expiration policies deliberately

If a policy does not specify an expiration, the documented default is one minute. Relying on that implicit value can produce surprising staleness, so set a duration that matches the endpoint’s business requirement and state the tolerance in code review or documentation.

builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(policy =>
        policy.Expire(TimeSpan.FromSeconds(10)));

    options.AddPolicy("Products", policy =>
        policy.Expire(TimeSpan.FromSeconds(30)));
});

A base policy provides a broad default for endpoints that opt in without a more specific policy. Named policies let you give a product list, exchange-rate snapshot, or documentation page a different lifetime. The duration is a correctness decision, not merely a performance setting: a longer lifetime increases reuse while increasing the maximum age of data a client can receive.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Apply a named policy

Minimal API endpoints select a named policy with CacheOutput("PolicyName"):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
app.MapGet("/products", GetProducts)
   .CacheOutput("Products");

Controller actions can select a policy with the [OutputCache] attribute:

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    [HttpGet]
    [OutputCache(PolicyName = "Products")]
    public IActionResult Get() => Ok(_catalog.GetProducts());
}

Keep policy names descriptive. A name such as Products should identify the data contract and its variation rules, not just the fact that caching is enabled.

Design cache keys so responses stay correct

The default cache key includes the request scheme, host, port, path, and query string. That is a safe starting point for many simple routes, but it can be broader than necessary or insufficient for an endpoint whose output depends on other request inputs.

Vary by only the query parameters that matter

If only the culture query parameter changes the representation, configure that parameter explicitly:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("Culture", policy =>
        policy.SetVaryByQuery("culture"));
});

Narrow variation can improve the hit rate and reduce memory use because irrelevant query parameters do not create separate entries. Do not narrow it if another parameter changes the body, status, or important headers.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Available variation controls

  • SetVaryByQuery varies by selected query-string keys.
  • SetVaryByHeader varies by headers such as an explicitly supported representation or language header.
  • SetVaryByRouteValue varies by route parameters.
  • SetVaryByHost separates host names when the same route serves different tenants or sites.
  • VaryByValue lets you derive a custom value for an input not covered by the standard selectors.
  • Case-sensitive path configuration controls whether path casing creates distinct cache entries.

Think of the key as a complete list of response-driving inputs. Under-varying can leak one representation to a request that should receive another. Over-varying is safer for correctness but lowers reuse and consumes more storage. Document why each varied input exists and test two requests that differ only in that input.

Headers, routes, and custom context

Use header variation only for headers that actually alter the response. For example, if your endpoint emits different languages based on a supported language header, include that header and normalize the accepted values in application logic. If a route value such as {version} changes the contract, vary by that route value. For a tenant resolved from a trusted host or custom request context, use host variation or a custom value and verify that tenant resolution occurs before the cache key is evaluated.

Respect the built-in safety boundaries

By default, output caching stores only HTTP 200 responses to GET or HEAD requests. Responses that set cookies and responses to authenticated requests are excluded by default. These defaults reduce the chance of caching a mutation, an error, a private session, or a user-specific representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

They are guardrails, not a substitute for endpoint review. Explicitly exclude a response when it contains personal information, authorization-dependent fields, one-time tokens, or rapidly changing state. If an authenticated endpoint is genuinely shareable, prove that its representation is identical for every authorized caller and design variation around the actual access boundary; otherwise leave it uncached.

Check response behavior before opting in

  • Confirm the route is safe to replay for another request with the same key.
  • Confirm no cookie, session identifier, CSRF token, or per-user link is emitted.
  • List every query, route, host, header, and custom value that changes the payload or status.
  • Decide what a caller may observe during the expiration window.
  • Verify that authorization runs before output-cache middleware.

Invalidate related entries with tags

Expiration alone is useful for time-bounded freshness, but a write operation often knows exactly when cached data became obsolete. Tags let you evict a group of entries together, such as every endpoint that exposes products.

app.MapPost("/purge/{tag}", async (IOutputCacheStore store, string tag) =>
{
    await store.EvictByTagAsync(tag, default);
    return Results.NoContent();
});

Attach the same tag to the relevant policy or route group, then call the store after a successful update. A base policy can attach a broad tag for a route group, while a narrower tag can represent one domain area. A broad tag can also support a whole-cache eviction workflow when an operational event requires it.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

A purge endpoint is an administrative capability. Protect it with authentication, authorization, network controls, auditing, and rate limits appropriate to your environment. Do not expose an unauthenticated route that lets any caller erase hot entries or repeatedly force expensive origin work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prevent cache stampedes and choose storage

When an entry expires under heavy traffic, many requests can otherwise regenerate the same response at once. ASP.NET Core enables resource locking by default to mitigate this cache-stampede or thundering-herd behavior. Microsoft’s documentation states: “By default, resource locking is enabled to mitigate the risk of cache stampede and thundering herd.”

Keep the default locking behavior unless you have measured a workload where waiting requests create a worse outcome than duplicate regeneration. You can disable it deliberately:

builder.Services.AddOutputCache(options =>
{
    options.AddPolicy("NoLock", policy =>
        policy.SetLocking(false));
});

Disabling locking can make sense for very cheap handlers or workloads where lock contention is demonstrably harmful, but it can multiply database and downstream calls during an expiry burst. Test with the same concurrency and expiry pattern your production traffic produces.

In-process versus distributed storage

In-process storage is simple and fast for a single application instance, but each instance has its own entries. A request routed to a different instance may miss even when another instance has a fresh response, and a restart clears local entries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a multi-instance deployment, a distributed store can provide a shared cache. Microsoft documents a StackExchange.Redis output-cache package for distributed storage; verify the package and ASP.NET Core version compatibility before deploying. Distributed storage adds network latency, serialization cost, capacity planning, availability concerns, and operational credentials, so compare those costs with the origin work saved.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Design choice Strength Trade-off Best fit
In-process output cache Lowest access overhead and simplest setup Entries are local to one instance and disappear on restart Single-instance services or workloads tolerant of per-instance misses
Distributed output cache Shared entries across application instances Network, serialization, capacity, and dependency overhead Scaled-out services that need consistent reuse across nodes
Time-based expiration Easy to reason about and configure Can serve stale data until the duration ends Data with a known maximum staleness window
Tag-driven eviction Removes related entries immediately after a known change Requires reliable purge calls and protected operations Catalogs, configuration, or other write-triggered domains
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Build a policy around the endpoint, not a blanket rule

A practical policy review uses six questions:

  1. Freshness: How old may a response be before it is unacceptable?
  2. Correctness: Which request inputs alter the representation, status, or important headers?
  3. Scope: Is the response public, tenant-scoped, authenticated, or user-specific?
  4. Invalidation: Is time-based expiry sufficient, or must a write trigger tag eviction?
  5. Concurrency: Should default resource locking protect the origin during expiry?
  6. Topology: Will local entries be adequate, or does the service need shared distributed storage?

For example, a public product list might use a 30-second named policy, vary by a culture query parameter, carry a product tag, and be evicted after a catalog update. A user dashboard should normally remain uncached because its output depends on identity and authorization. These are different correctness problems even if both handlers return JSON.

Verify that caching is actually working

Do not infer success from a faster local request. Validate behavior with repeatable checks:

  • Send the same eligible GET twice and confirm the second request does not execute the origin work.
  • Change one response-driving query, route value, host, or header and confirm it produces the correct separate representation.
  • Send an authenticated request and verify that private content is not served from a public entry.
  • Trigger a successful write, evict its tag, and confirm the next read reflects the update.
  • Wait through expiration and observe whether one request regenerates the entry while concurrent requests avoid duplicate origin work.
  • Restart one instance or route traffic to another instance to understand local-cache miss behavior.

Instrument cache hits and misses, endpoint latency, origin execution time, database and downstream call volume, cache memory or distributed-store usage, eviction counts, lock wait behavior, and the age of data returned. Compare these metrics before and after enabling a policy. The framework documentation does not establish a universal percentage reduction for latency, CPU, or throughput.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting common failures

Every request still runs the handler

Check that AddOutputCache is registered, UseOutputCache is in the active pipeline, and the endpoint has CacheOutput, a named policy, or [OutputCache]. Then confirm the response is a GET or HEAD with status 200 and does not set a cookie or come from an authenticated request excluded by the defaults.

Different users see the same private response

Remove output caching from the endpoint immediately, verify middleware ordering, and inspect every cache-key component. Do not attempt to repair a private endpoint by adding one guessed header; identify the complete authorization or identity boundary and either vary by all of it or keep the endpoint uncached.

Requests return the wrong language, tenant, or filter

List every input used by the handler and compare it with the policy’s variation settings. Add the missing query, header, route, host, or custom value. Also check path-casing behavior and any normalization that causes distinct inputs to collapse into one key.

Updated data remains visible

Shorten the expiration only if that staleness window is acceptable. For immediate consistency after a write, assign a shared tag to the affected read policies and call EvictByTagAsync after the write succeeds. Ensure the purge code reaches the same storage used by the readers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Origin load spikes at expiry

Keep resource locking enabled, inspect whether several keys expire simultaneously, and consider staggered durations or explicit invalidation for synchronized workloads. If locking was disabled, restore it and re-test under production-like concurrency.

Hit rate is unexpectedly low

Look for unnecessary query-string or header variation, multiple hosts or instances using separate local stores, very short expirations, and frequent tag evictions. Remove only variation that you can prove does not affect the response; a higher hit rate is not a success if it serves an incorrect representation.

A deployment checklist

  • Register output-cache services and middleware in every environment where the policy is expected.
  • Place output caching after authentication and authorization.
  • Opt in only endpoints that can safely replay a stored response.
  • Set an explicit expiration for each important policy.
  • Map all response-driving inputs into the cache key.
  • Choose tags and protected purge operations for write-heavy domains.
  • Keep resource locking unless measured evidence supports disabling it.
  • Select local or distributed storage based on instance topology and consistency needs.
  • Load-test hit, miss, expiry, purge, and concurrent-request paths.
  • Monitor freshness impact as well as latency and infrastructure savings.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

.NET Web APIASP.NET Corecache invalidationcache stampedeoutput cachingRedisWeb API performance

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.