Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

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

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Asp.Net Core

ASP.NET Core: Fix a Request That Keeps Running After the Client Disconnects Because the Action Never Checked HttpContext.RequestAborted

- 15.10.26 - ErcanOPAK

⚙️ The Request That Outlived the Client That Sent It

Every HttpContext carries a RequestAborted CancellationToken that fires the moment the client disconnects, closes the tab, or hits its own timeout – but it only does anything if the action actually passes it to the work being awaited. An action that ignores it keeps running a database query, an external API call, or a report generation job to completion for a response nobody is still there to receive.

🔎 The Problem

[HttpGet("report/{id}")]
public async Task<IActionResult> GetReport(int id)
{
    // No CancellationToken parameter at all, so there's
    // nothing here that could ever observe the client
    // giving up. The query and the PDF render both run
    // to completion even if the browser tab closed a
    // full minute ago.
    var data = await _db.Orders
        .Where(o => o.ReportId == id)
        .ToListAsync();

    var pdf = await _reportBuilder.RenderAsync(data);
    return File(pdf, "application/pdf");
}

✅ Fix: Thread RequestAborted Into Every Awaited Call

  • Add a CancellationToken parameter to the action and let model binding fill it from HttpContext.RequestAborted automatically – then pass that same token into every ToListAsync, HttpClient call, and long-running helper the action awaits, so each one can stop the moment the client leaves.
  • Treat a resulting OperationCanceledException as the expected shutdown path, not an error – let ASP.NET Core’s built-in handling convert it into a quiet, logged cancellation instead of wrapping it in your own error-reporting pipeline where it’ll look like a real failure.
  • For work that genuinely shouldn’t stop just because the HTTP request did (a payment that already started, a write that must finish once begun), that’s a deliberate design choice – hand it off to a background job explicitly instead of letting it ride along on an HTTP request’s cancellation token by accident.

⚠️ Why This Is Easy to Miss

  • A request that completes in under a second almost never gets cancelled mid-flight, so this only shows up as wasted database and CPU load on the slow, expensive endpoints – exactly the ones where the waste matters most.
  • It’s invisible in local testing because you’re the only client and you rarely close the tab mid-request on purpose – it surfaces later as database load that doesn’t match the number of responses actually being sent.

A client that hung up isn’t waiting for an answer anymore – an action that doesn’t check for that keeps working for an audience that already left.

— Backend Architect

Related posts:

.NET Core: Configure CORS for API Security

.NET Core: Configure CORS for API Security

.NET Core: Reduce Docker Image Build Time with Layer Caching Optimization

.NET Core: Reduce Docker Image Build Time with Layer Caching Optimization

.NET Core: Use File-Scoped Namespaces to Reduce Indentation

.NET Core: Use File-Scoped Namespaces to Reduce Indentation

Views: 12

Post navigation

ASP.NET Core: Fix Duplicate Records Created When a Client Retries a POST Because There’s No Idempotency Key Check
SQL Server: Fix a Query Plan Cache Bloated by Ad-Hoc Queries Because Literal Values Were Never Parameterized

Leave a Reply Cancel reply

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

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

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