Each request to your controller will create a new instance of the class to process that request. The request to the
StopDownloadOperation
action will not have access to the
CancellationTokenSource
created by the
DownloadFiles
action.
If you're triggering the download via a Javascript call, you may be able to use
an AbortController
instead[
^]:
[HttpPost]
public async Task<IActionResult> DownloadFiles(DownloadFilesModel downloadFilesModel, CancellationToken cancellationToken)
{
var successFiles = await _downloadManager.DownloadAsync(downloadFilesModel.param1, downloadFilesModel.param2, cancellationToken);
return Ok(successFiles);
}
const startButton = document.getElementById("startDownloadButton");
const stopButton = document.getElementById("stopDownloadButton");
let abortController = null;
startButton.addEventListener("click", async (e) => {
e.preventDefault();
abortController?.abort();
abortController = new AbortController();
stopButton.disabled = false;
startButton.disabled = true;
try {
const response = await fetch(url, {
method: "POST",
body: { ... },
signal: abortController.signal
});
if (!response.ok) {
console.error(response.status, response.statusText, errorMessage);
return;
}
const data = await response.json();
} finally {
abortController = null;
stopButton.disabled = true;
startButton.disabled = false;
}
});
stopButton.addEventListener("click", (e) => {
e.preventDefault();
abortController?.abort();
});
Fetch API - Web APIs | MDN[
^]
The
CancellationToken
passed in to the action should automatically be cancelled if the client aborts the request.