When a client closes a connection during a long running web operation, it could be beneficial for some systems to take notice and stop work on creating the response.
There are two techniques you can use to detect an aborted request in ASP.NET Core. The first approach is to look at the RequestAborted
property of HttpContext
.
if (HttpContext.RequestAborted.IsCancellationRequested) { // can stop working now }
RequestAborted
is a CancellationToken
. Another approach is to allow model binding to pass this CancellationToken
as an action parameter.
[HttpGet] public async Task<ActionResult> GetHardWork(CancellationToken cancellationToken) { // ... if (cancellationToken.IsCancellationRequested) { // stop! } // ... }
And yes, both approaches work with the exact same object.
if(cancellationToken == HttpContext.RequestAborted) { // this is true! }
If you are hosted in IIS or IIS Express, the ASP.NET Core Module (ANCM) doesn’t tell ASP.NET Core to abort a request when the client disconnects. We know the ANCM is having some work done for the 2.2 release and moving to a faster in-process hosting model. Hopefully the 2.2 work will fix this issue, too.