In this blog post, HSD’s Cloud and Integration Architect Craig Letcher looks at how to cancel HTTP request with ASP.Net MVC 5.

I recently had a project where a long-running extract job from a web site would take up to a minute when the user had chosen to export all data, about 100,000 rows. The client asked if there was a way for the user to cancel this if the user thinks it was taking to long. On top of this, I thought if the user navigates away by using the browser back button, enters a new URL or simply press the stop button on the browser if I could stop the process.

Browsers will send a cancelled status back to the server for pending request.

In Chrome, you can see this behaviour in the developer tools:

The browser will automatically send the cancelled status back to the server when the user presses stop, back or navigates away from the page. However to stop the process programmatically we can use Javascript call window.stop(); to achieve the same as pressing the stop button on the browser.

Note: window.stop won’t work in IE but will in all other major browsers.

Now on the server side for an ASP.Net MVC 5 application (a similar technique can be used for ASP.NET Core MVC and Web API), you need to include as a parameter to the method a CancellationToken.

You then need to combine it with the Response ClientDisconnectedToken in a CancellationTokenSource.

CancellationToken disconnectedToken = Response.ClientDisconnectedToken; var source = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disconnectedToken);

You can then pass it to any async process that accepts a CancellationToken and the process will be automatically stopped.

You can also manually check the token throughout your code, say for instance in a for loop.

                if (source.Token.IsCancellationRequested)

By calling the ThrowIfCancellationRequested method an OperationCanceledException is throw so you can clean up before you end the process. In my case I was using a memory stream for a file download that I closed.

That’s it your request has been cancelled and resources are freed from your servers, even if the user doesn’t intentionally cancel the request, by moving away from the page its automatically done.