I check a lot of tutorials and everywhere developers describe that if I add CancellationToken to my request then when the request become cancelled then flag IsCancellationRequested should change from fals to true. But be honest it doesn’t work for me when I run it for .NET 7 & 8. Mabye someone tell me what I’m doing wrong becuase maybe I don’t understand something.
Simple example bellow, when I test it via postman or Swagger and cancel it I have never got status 499.
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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("/long-running-request", async (CancellationToken cancellationToken) =>
{
var randomId = Guid.NewGuid();
var results = new List<string>();
for (int i = 0; i < 100; i++)
{
if (cancellationToken.IsCancellationRequested)
return Results.StatusCode(499);
await Task.Delay(1000);
var result = $"{randomId} - Result {i}";
Console.WriteLine(result);
results.Add(result);
}
return Results.Ok(results);
})
.WithName("GetAllData")
.WithOpenApi();
app.Run();
I try to figured out how can I cancel my API request and detect it to stop processing my logic in endpoint.
Łukasz Zapała is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.