Код: Выделить всё
public class CancelInTimeMiddleware : IMiddleware
{
// Better understanding of why we can't stop all requests very easiliy: https://stackoverflow.com/a/52660992/619465
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var originalCt = context.RequestAborted;
using (var timoutTS = CancellationTokenSource.CreateLinkedTokenSource(originalCt))
{
timoutTS.CancelAfter(10000); // Always cancel after 10 seconds
context.RequestAborted = timoutTS.Token;
await next(context);
}
}
}
Код: Выделить всё
public static async Task GetTimer(int delaySeconds, CancellationToken cancellationToken)
{
logger.LogInformation("Entering the wait!");
await Task.Delay(delaySeconds * 1000, cancellationToken);
//catch (TaskCanceledException) -> I also want to handle cases where this is forgotten.
return Results.Json(new { Message = "Waiting is done" });
}
Код: Выделить всё
class SimpleExceptionHandler : IExceptionHandler
{
public async ValueTask TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
// Your response object
var error = new { message = exception.Message };
await httpContext.Response.WriteAsJsonAsync(error, cancellationToken);
return true;
}
}
Код: Выделить всё
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler();
builder.Services.AddSingleton();
var app = builder.Build();
app.UseExceptionHandler(_ => { });
app.UseMiddleware();
app.MapGet("wait/{delaySeconds:int}", TestEndPointsImplementations.GetTimer);
app.Run();
Подробнее здесь: https://stackoverflow.com/questions/792 ... ionhandler
Мобильная версия