controllercancellation-token

How can I add CancellationToken to my Controller?


I know, there are lots of answers here about CancellationToken, but for my problem, I have not found any solution yet. I just want to cancel this call, when the user starts a new one:

[HttpGet]
[Route("getUsers")]
public async Task<IEnumerable<string>> GetUsersAsync(string query)
{
    return await _userService.GetUsersAsync(query);
}

I found something like that, but I do not know where the cancellationToken come from and where I have to pass it from here:

[HttpGet]
[Route("getUsers")]
public async Task<IEnumerable<string>> GetUsersAsync(string query, CancellationToken cancellationToken)
{
    return await _userService.GetUsersAsync(query, cancellationToken);
}

Solution

  • I just want to cancel this call, when the user starts a new one

    There isn't a good way to do that in a web API, which is generally stateless. So there's no (good) way to detect "when the user starts a new one".

    This is normally done on the client side, where "when the user starts a new one" is easy to detect. The old request is cancelled and a new one is made.

    Your web API can detect a request being cancelled by just taking a CancellationToken. The cancellation token is provided by ASP.NET and is triggered when a request is cancelled.

    To respond to the cancellation request, the most common pattern is to just pass it down to whatever APIs you call. In this case your GetUsersAsync call would take a CancellationToken and pass it down to whatever DB API it uses.