'Swagger does not cancel Request

I want to cancel a simple GET method, which is waiting 10 seconds and returns a string. It's capsulated in a try-catch block. It's working in the CLI and in Chrome, but not with Swagger.

[HttpGet("wait")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public async Task<string> Wait(CancellationToken userCancellationToken)
{
    try
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine($"Waited {i} seconds, CancellationRequested: {userCancellationToken.IsCancellationRequested}");
            userCancellationToken.ThrowIfCancellationRequested();
            await Task.Delay(1000);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        throw;
    }
     return "OK";
}

In Chrome, I canceled the operation by "stop loading page" (X - left of the URL) and by closing the tab (http://localhost:5001/api/wait).

In the CLI I used

curl -X 'GET' \
  'http://localhost:5001/wait' \
  -H 'accept: application/json'

(recommended by swagger, itself)

In both cases (CLI & browser) the server prints out:

Waited 0 seconds, CancellationRequested: False
Waited 1 seconds, CancellationRequested: False
Waited 2 seconds, CancellationRequested: False
Waited 3 seconds, CancellationRequested: True
The operation was canceled.

I'm using the latest version of Swashbuckle and net6.0:

<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />

Cancelling in swagger does not do anything (log prints till the end and CancellationRequested: False, also Chrome's network window shows the response)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source