How to Let Requests Finish When an ASP.NET Core App Shuts Down (C#)
When an ASP.NET Core app stops, it doesn't drop the requests it's still answering straight away: it stops taking new ones and gives the rest 30 seconds. A request that needs longer is cut off, and the caller gets an error instead of an answer. Here's that happening to a 40-second request, and the one setting that lets it finish.
Apps stop more often than you might think. You press Ctrl+C while you work on one. A hosting platform stops it when it scales in or replaces it with a new version, and it does that by sending the app the signal SIGTERM. ASP.NET Core handles Ctrl+C and SIGTERM the same way: it shuts down gracefully, within a time limit called the shutdown timeout. This guide shows what that limit does to a slow request, and two ways to change it.
Syntax
In Program.cs, before builder.Build():
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(<seconds>);
});
Or, without changing the code, as an environment variable that is set when the app starts:
DOTNET_SHUTDOWNTIMEOUTSECONDS=<seconds>
| Part | What it is |
|---|---|
builder.Services.Configure<HostOptions> | Changes the options of the host, the part of ASP.NET Core that starts and stops the app |
options | The host's options, a HostOptions object |
ShutdownTimeout | Specifies the amount of time to wait for the host to shut down. The default is 30 seconds |
TimeSpan.FromSeconds(<seconds>) | The limit. <seconds> is how long requests that are still running get to finish after the app is told to stop |
DOTNET_SHUTDOWNTIMEOUTSECONDS | The same limit from an environment variable: the host setting shutdownTimeoutSeconds with the DOTNET_ prefix. ASPNETCORE_SHUTDOWNTIMEOUTSECONDS works too |
<seconds> in the variable | A whole number of seconds. Microsoft lists the setting's type as int |
Step 4 shows how to set the variable in bash, zsh and PowerShell.
The Example
SlowReport is a small web app with one address, /report, that takes 40 seconds to answer, like a report that reads a lot of data. Each run sends it one request and stops the app while that request is still being answered: first as the app comes, then with the limit raised to 60 seconds in code, and then with the environment variable instead.
Step 1: Create the App
dotnet new web --no-https -n SlowReport
cd SlowReport
dotnet new web creates an empty ASP.NET Core app from the template called ASP.NET Core Empty. --no-https leaves HTTPS out, so the example needs no development certificate, and -n SlowReport names the project and its folder. cd moves into that folder. The first command prints:
The template "ASP.NET Core Empty" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/SlowReport/SlowReport.csproj:
Restore succeeded.
Replace everything in Program.cs with this:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});
app.Run();
What each part does:
WebApplication.CreateBuilder(args)andbuilder.Build()set up the app, as in every new ASP.NET Core project.app.MapGet("/report", ...)answers GET requests to/reportwith the code after it.app.Logger.LogInformationwrites a line to the terminal under the app's name,SlowReport, so you can see when the report starts and when it finishes.await Task.Delay(TimeSpan.FromSeconds(40))waits 40 seconds. It stands in for slow work, such as a big database query.- The text it returns,
Your report is ready., is the answer the caller gets. app.Run()starts the app and keeps it running until it's told to stop.
Step 2: Stop the App While a Request Is Running
You need two terminals. In the first one, in the SlowReport folder, start the app:
dotnet run --no-launch-profile --urls http://localhost:5310
dotnet run builds the app and starts it. --no-launch-profile skips Properties/launchSettings.json, where dotnet new picked a random port, and --urls makes the app listen on port 5310 instead. How to Run an ASP.NET Core App on a Fixed Port explains both. Wait until it prints Application started. Press Ctrl+C to shut down.
In the second terminal, ask for the report:
- bash / zsh
- PowerShell
curl -sS -w '\n%{http_code} after %{time_total}s\n' http://localhost:5310/report
Invoke-RestMethod http://localhost:5310/report
curl sends a GET request and prints the answer. -sS hides its progress meter but still shows errors, and -w adds a last line with the HTTP status code and how long the request took. In PowerShell, Invoke-RestMethod sends the request and prints the answer.
Terminal 2 now waits for the report. Straight away, while it's still waiting, go back to Terminal 1 and press Ctrl+C. Terminal 1 shows:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
Report started. is the request arriving. ^C is how the terminal shows Ctrl+C, and Application is shutting down... is the app beginning to stop. Then nothing more: Report finished. never came, and about 31 seconds after Ctrl+C the app ended. Terminal 2 got this:
- bash / zsh
- PowerShell
curl: (56) Recv failure: Connection reset by peer
000 after 31.285464s
Invoke-RestMethod: Unable to read data from the transport connection: Connection reset by peer.

The caller got no report. The app closed the connection while the request was still running, which both tools report as "Connection reset by peer", and curl's 000 means that no HTTP status code arrived at all. The 31.3 seconds are the moment before Ctrl+C plus the 30-second limit. I ran the PowerShell command in PowerShell 7.6 on macOS.
That's what Microsoft describes for the end of the limit: If the timeout expires, the pending connections and requests are aborted forcefully, which can cause errors in the logs and to the clients.
Step 3: Give Requests More Time
Add these lines to Program.cs, between the var builder line and var app = builder.Build();:
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});
HostOptions holds the settings of the host, and ShutdownTimeout is how long it waits for running requests when the app stops. 60 seconds gives the 40-second report room to finish. The lines have to come before builder.Build(): after it, the app stops at startup with an InvalidOperationException.
The complete Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<HostOptions>(options =>
{
options.ShutdownTimeout = TimeSpan.FromSeconds(60);
});
var app = builder.Build();
app.MapGet("/report", async () =>
{
app.Logger.LogInformation("Report started.");
await Task.Delay(TimeSpan.FromSeconds(40));
app.Logger.LogInformation("Report finished.");
return "Your report is ready.";
});
app.Run();

Do the same as in Step 2: start the app in Terminal 1 with the same command, ask for the report in Terminal 2, and press Ctrl+C in Terminal 1 while Terminal 2 waits. Terminal 1:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
info: SlowReport[0]
Report finished.

This time Report finished. came after Application is shutting down...: the app waited for the request. It didn't wait the whole 60 seconds, though. It ended about 39 seconds after Ctrl+C, as soon as the report was done. Microsoft puts it this way: If they're all complete before the timeout, the server returns control to the host sooner. Terminal 2 got the report:
- bash / zsh
- PowerShell
Your report is ready.
200 after 40.052716s
Your report is ready.
Status 200, 40 seconds after it asked: the whole report, even though the app was told to stop 39 seconds before it was ready.
Step 4: Set It Without Changing the Code
The same limit can come from an environment variable. That suits a server or a hosting platform, where each environment can have its own value without a new build. To try it, take the four lines from Step 3 out of Program.cs again, so that it's back to the code from Step 1. Then start the app with the variable:
- bash / zsh
- PowerShell
DOTNET_SHUTDOWNTIMEOUTSECONDS=60 dotnet run --no-launch-profile --urls http://localhost:5310
$env:DOTNET_SHUTDOWNTIMEOUTSECONDS = "60"
dotnet run --no-launch-profile --urls http://localhost:5310
In bash and zsh, NAME=value in front of a command sets the variable for that one command. In PowerShell, $env: sets it for the rest of the session in that window, so every app you start from it afterwards gets it.
Ask for the report in Terminal 2 and press Ctrl+C in Terminal 1, as before. Terminal 1:
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5310
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/SlowReport
info: SlowReport[0]
Report started.
^Cinfo: Microsoft.Hosting.Lifetime[0]
Application is shutting down...
info: SlowReport[0]
Report finished.

And Terminal 2:
- bash / zsh
- PowerShell
Your report is ready.
200 after 40.052788s
Your report is ready.
The same result as Step 3, with no change to the code. ASPNETCORE_SHUTDOWNTIMEOUTSECONDS=60 worked the same way in my run: Microsoft lists both prefixes, DOTNET_ and ASPNETCORE_, for the host's settings.
What Happens When an ASP.NET Core App Stops
Microsoft's documentation of the .NET Generic Host, which runs every ASP.NET Core app, describes the order:
- A signal to stop arrives. Ctrl+C, or SIGTERM, which other apps send to stop yours (
docker stopis Microsoft's example). The host's console lifetime listens for both and attempts to stop the host gracefully. - The app is told. The host signals
ApplicationStopping, which your own code can listen to, and asks the web server, Kestrel, to stop, with the shutdown timeout. - New connections are refused. In Microsoft's words, Kestrel and Http.Sys close their port bindings and stop accepting new connections.
- Running requests get the rest of the timeout. When the last one finishes, the app ends. When the time runs out first, the rest are cut off.
You can watch the third step happen. In another run with Step 3's code, I sent a second request 2 seconds after Ctrl+C, while the first one was still running:
curl: (7) Failed to connect to localhost port 5310 after 0 ms: Couldn't connect to server
000 after 0.000364s
The new request was refused at once, and the first one still got its report, 40 seconds after it started.
The shutdown timeout only applies when the app is asked to stop. A crash, or a forced stop with SIGKILL, ends the process without it. About those, Microsoft says: The hosting code isn't responsible for handling these scenarios.
Choose the Limit
- Longer than your slowest request. Here the report takes 40 seconds and the limit is 60. A limit far above your slowest request only makes a stuck request hold up the shutdown longer.
- Shorter than whatever stops the app. A hosting platform waits only so long after SIGTERM before it ends the app with SIGKILL. Azure Container Apps, for example: If your application doesn't respond within 30 seconds to the SIGTERM message, then SIGKILL terminates your container. Its setting for that wait,
terminationGracePeriodSeconds, defaults to 30 seconds, and Microsoft's advice for it is: Set this value longer than the expected cleanup time for your process. So a 60-second shutdown timeout needs a grace period of more than 60 seconds there. I didn't run this example on a hosting platform: this part is what Microsoft documents.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| A shutdown timeout shorter than your slowest request | Requests still running when the app stops are cut off, and the caller gets a connection error | Set the timeout above your slowest request |
Configure<HostOptions> after builder.Build() | The app stops at startup with The service collection cannot be modified because it is read-only | Put it before builder.Build() |
| Setting the environment variable in a different terminal from the one that starts the app | The app only gets the variables of the terminal it starts from, so the default 30 seconds applies | Set it in the terminal that runs dotnet run, or where your server starts the app |
| A shutdown timeout longer than the platform's grace period | The platform ends the app with SIGKILL before the timeout is up | Make the platform's grace period longer than the shutdown timeout |
| Counting on the timeout after a crash or a forced kill | Nothing waits: the host doesn't handle those | Keep long work in a form that can be retried |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Callers get Connection reset by peer or Unable to read data from the transport connection when you stop or redeploy the app | Their requests were still running when the shutdown timeout ran out | Raise ShutdownTimeout above your slowest request |
| Requests are still cut off after about 30 seconds | The new value didn't reach the app | Check that the code comes before builder.Build(), or that the variable is set where the app starts |
curl: (7) Failed to connect right after Ctrl+C | The app has stopped taking new connections, as it should | Send new requests to another copy of the app before you stop this one |
FAQ
What is the default shutdown timeout?
30 seconds. Microsoft notes that in .NET 5 and earlier it was 5 seconds.
Does the app always wait for the whole timeout?
No. It ends as soon as the last request finishes. In Step 3 that was about 39 seconds after Ctrl+C, not 60.
Do new requests get in while the app waits?
No. From the moment shutdown starts, new connections are refused: the second request in the run above failed after 0 ms.
Does this also work when Docker or a hosting platform stops the app?
They send SIGTERM, and Microsoft lists SIGTERM among the signals that make the host shut down gracefully, the same way as Ctrl+C. I tested with Ctrl+C. Check how long the platform waits before it forces the app to stop, as in Choose the Limit.
Does the timeout cover background services too?
Yes. Microsoft lists it among what the host does during the timeout: Attempts to stop hosted services, logging errors for services that fail to stop. And its advice: If services require more time to stop, increase the timeout.
Conclusion
ASP.NET Core gives requests that are still running 30 seconds when it stops, and cuts off the rest. Raise ShutdownTimeout with Configure<HostOptions> before builder.Build(), or set DOTNET_SHUTDOWNTIMEOUTSECONDS, to a value above your slowest request, and make sure whatever stops the app waits longer than that.
Additional Resources
- .NET Generic Host in ASP.NET Core: Shutdown timeout — the setting, its default and its environment variable.
- .NET Generic Host: Host shutdown — the signals the host handles, and what happens to requests when an app stops.
- HostOptions.ShutdownTimeout — the property's reference.
- Application lifecycle management in Azure Container Apps — SIGTERM, then SIGKILL after 30 seconds.
