I am trying to disable the automatically enabled "Ctrl+C" shutdown for an API Host created in an ASP.NET Core Web Application. The same question was asked previously here, but it doesn't work for me using the code below -- the "Press Ctrl+C" message is still shown on startup and, indeed, pressing Ctrl+C stops the application.
How can I turn off this behavior?
Adding Console.CancelKeyPress handler to trap the Ctrl-C doesn't work -- setting 'Cancel = True' doesn't stop the ASP.NET host from seeing the Ctrl-C and halting.
Here's the code:
public static void Main(string[] args) {
var tokenSource = new CancellationTokenSource();
var task = CreateHostBuilder(args).Build().RunAsync(tokenSource.Token);
while (!task.IsCompleted) {
// TODO: Other stuff...
Thread.Sleep(1000);
};
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
And here's the output on application start (note that the "Press Ctrl+C..." message is still there):
info: Microsoft.Hosting.Lifetime[0] Now listening on: https://localhost:5001 info: Microsoft.Hosting.Lifetime[0] Now listening on: http://localhost:5000 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: <path>