How to cancel incoming request in .net core 6 API?

69 views Asked by At

In .NET core 6 API application. I would like to cancel the incoming request if it's take more than x minutes to complete the call in service layer and return with 504 status code. In my service layer all i have is regular async method that make a call to active directory lookup.

I am using IIS to host this API. I have try settings in IIS itself but no luck.

There is attribute called requestTimeout in web.config but it doesn't work with in-process hosting.

2

There are 2 answers

1
j4rey On

You can configure an endpoint to timeout by calling WithRequestTimeout, or by applying the [RequestTimeout] attribute

using Microsoft.AspNetCore.Http.Timeouts;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRequestTimeouts();

var app = builder.Build();
app.UseRequestTimeouts();

app.MapGet("/", async (HttpContext context) => {
    try
    {
        await Task.Delay(TimeSpan.FromSeconds(10), context.RequestAborted);
    }
    catch (TaskCanceledException)
    {
        return Results.Content("Timeout!", "text/plain");
    }

    return Results.Content("No timeout!", "text/plain");
}).WithRequestTimeout(TimeSpan.FromSeconds(2));
// Returns "Timeout!"

app.MapGet("/attribute",
[RequestTimeout(milliseconds: 2000)] async (HttpContext context) => {
    try
    {
        await Task.Delay(TimeSpan.FromSeconds(10), context.RequestAborted);
    }
    catch (TaskCanceledException)
    {
        return Results.Content("Timeout!", "text/plain");
    }

    return Results.Content("No timeout!", "text/plain");
    });
// Returns "Timeout!"

app.Run();

For apps with controllers, apply the [RequestTimeout] attribute to the action method or the controller class. For Razor Pages apps, apply the attribute to the Razor page class.

https://learn.microsoft.com/en-us/aspnet/core/performance/timeouts?view=aspnetcore-8.0&viewFallbackFrom=aspnetcore-6.0

1
Sudhesh Gnanasekaran On

If your API method is async, use the cancellation token to cancel it.

cancellati0nTokenInstance.CancelAfter(3500);