Using a CancellationToken to Abort an ASP.NET Core Request
Anytime a connection to a long running process is made there is the risk that the connection will be terminated prior to the process completing. A Cancellation Token is used to notify a process that a request should be cancelled.
As part of the connection to an ASP.NET Core Controller there is the HttpContext. This provdes access the a CancellationToken.
To test if the process should cancelled you check the status of the RequestAborted
.IsCancellationRequested
property within the HttpContext.
[HttpGet]
public async Task<IActionResult> Get(IHttpContextAccessor httpContext)
{
if(httpContext?.HttpContext?.RequestAborted.IsCancellationRequested)
{
// Stop processing
}
}
The RequestAborted
is an instance of a CancellationToken.
Another way to access the CancellationToken is to pass it as part of the Dependency Injection (DI) into the Controller.
[HttpGet]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
// ...
if(cancellationToken.IsCancellationRequested)
{
// Stop processing
}
// ...
}
Once the cancellation request has been detected the process should gracefully stop the processing and return.
You must be logged in to see the comments. Log in now!