How to use .NET CancellationTokens with Fetch AbortController API

94 views Asked by At

I'm trying to use CancellationTokens to cancel long running requests if the Fetch request I do in my front end is cancelled/aborted. I'm using Fetch AbortController / AbortSignal to cancel requests that take too long to run.

I've created a minimal web API demonstrating my issue:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/test", async (CancellationToken ct) =>
{
    while (!ct.IsCancellationRequested)
    {
        await Task.Delay(1000, ct);
    }
    return "complete";
});

app.Run();

In the front-end, I do a fetch request like so:

const response = await fetch('https://localhost:5429/test', { signal: AbortSignal.timeout(2500) });

In my browser console I can see that the request is actually aborted after 2500ms: Fetch request being cancelled However, the CancellationToken in the backend is never updated to cancel the request, and thus keeps running indefinitely.

Am I misunderstanding how CancellationTokens work, or am I missing a part of the implementation?

0

There are 0 answers