Search code examples
.netasp.net-core.net-coreiis-expresscancellation-token

Cancellation token in iis not triggering


I have an API with .net core 2.1 and use cancellation tokens in actions. When i run the project with iis and make a simple request in browser, after i cancel it, it doesn't work as expected and run all methods with cancellation token passed to them. But when i run the project using the kestrel server, cancelling the request causes the server to work as expected. why is that?

    [HttpGet("get")]
    public async Task<IActionResult> GetSome(CancellationToken ct)
    {

        _logger.LogInformation("The slow Request Start");
        try
        {
            await Task.Delay(10_000, ct);
            _logger.LogCritical("Successful");
        }
        catch (Exception)
        {
            _logger.LogInformation("Task Cancelled");
        }
        var message = "The request finished";

        _logger.LogInformation(message);

        return NoContent();
    }

Solution

  • Right now, this isn't possible when hosting ASP.NET Core up to 2.1 in (or more specific behind) IIS, the cancellation or connection loss won't be passed down to the ASP.NET Core application.

    Right now it only works when hosting/exposing directly through Kestrel or HTTP.SYS (formerly known as Weblistener).

    With ASP.NET Core 2.2 (from preview3 and later), the AspNetCoreModule has been updated to support this feature. However, its limited to IIS inprocess hosting and won't work when IIS acts as a mere reverse proxy.

    See the ASP.NET Core 2.2-preview3 Announcement blog.

    We added support for the ability to detect client disconnects when you’re using the new IIS in-process hosting model. The HttpContext.RequestAborted cancellation token now gets tripped when your client disconnnects.

    However, be aware that while in-process adds improved performance and less overhead, it also means that you can only have one application per App Pool hosted as in-process, if I remember correctly.