Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
Asp.Net Core

ASP.NET Core: Why the Response Caching Middleware Does Nothing on Any Endpoint That Sets a Cookie Header

- 03.10.26 - ErcanOPAK

🔧 The Response Caching Middleware That Refused Every Cookie-Bearing Response

ASP.NET Core’s response caching middleware follows the HTTP caching spec closely, and one of the rules it enforces without exception is that a response setting a cookie isn’t eligible to be cached – a shared cache storing and replaying a response meant to set a unique session cookie would hand that same cookie to every subsequent caller, which the spec correctly treats as unsafe. The part that surprises most teams is that this check applies to any cookie set anywhere in the pipeline for that request, including one set by completely unrelated middleware that runs long before the endpoint whose caching behavior everyone’s actually trying to debug.

🔎 The Problem

app.UseResponseCaching();

app.MapGet("/catalog/featured", (HttpContext ctx) =>
{
    // Some shared code path sets a tracking or session-affinity
    // cookie on every response through this app, including this
    // one - which has nothing to do with the data being returned.
    ctx.Response.Cookies.Append("sid", Guid.NewGuid().ToString());

    ctx.Response.GetTypedHeaders().CacheControl =
        new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromMinutes(5) };

    return Results.Ok(GetFeaturedProducts());
});
// ResponseCachingMiddleware silently skips caching ANY response that
// sets a cookie, by design (per HTTP caching semantics) - the
// Cache-Control header above is completely ignored, and every
// request re-executes GetFeaturedProducts() from scratch.

✅ Fix: Keep Cookies Off the Routes You Actually Want Cached

  • Move any cookie-setting logic (session IDs, tracking cookies, anti-forgery tokens) out of the handlers for routes that are actually meant to be cached, since the middleware’s skip behavior is correct per spec but easy to trigger by accident through shared middleware earlier in the pipeline.
  • Audit earlier middleware in the pipeline (authentication, anti-forgery, a custom logging or tracking component) for cookies being set globally on every response, rather than only on the routes that actually need them.
  • For an endpoint that must both set a cookie and be cacheable, use output caching with explicit per-endpoint policies instead of the older response caching middleware, or cache the underlying data directly (in memory or a distributed cache) rather than relying on HTTP-level response caching at all.

⚠️ Why This Is Easy to Miss

  • Nothing errors or logs a warning – the response still returns 200 with the right data and the right headers on the wire, it’s just never actually served from cache, which only becomes visible as consistently higher-than-expected load on the endpoint behind it.
  • The cookie responsible is frequently set by middleware registered well before the route itself (authentication or a shared diagnostics component), so a developer reviewing just the endpoint in question often finds no cookie-setting code there at all.

Response caching middleware isn’t ignoring your Cache-Control header – it’s following a rule from the HTTP spec you never knew applied, because a cookie showed up somewhere in the pipeline before your handler even ran.

— Backend Architect

Related posts:

.NET Core: Use Environment Variables for Configuration

.NET Core: Use Environment Variables for Configuration

ASP.NET Core: Fix Configuration Values Silently Reverting to Defaults in Production Because an Envir...

ASP.NET Core: Fix Configuration Values Silently Reverting to Defaults in Production Because an Envir...

Background Tasks the Right Way

Background Tasks the Right Way

Views: 13
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

WordPress: Fix an Image That Shows Broken on the Front End but Opens Fine Directly From the Media Library
The AI Prompt That Finds Every CSS Class Defined in Your Stylesheet but Never Used in Your HTML

Leave a Reply Cancel reply

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

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com