I want to do some clean up works when Control-C is pressed? How to achieve that in a Asp .Net Core Web Api App?
I simply want to write some logging messages to a text file when the app is closing.
I want to do some clean up works when Control-C is pressed? How to achieve that in a Asp .Net Core Web Api App?
I simply want to write some logging messages to a text file when the app is closing.
You can register a function to be invoked by ASP.NET Core when the application exits (via Ctrl-C
on the console) via IApplicationService.ApplicationStopping
in Startup.cs
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
....
var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
applicationLifetime.ApplicationStopping.Register(OnShutdown);
....
}
private void OnShutdown()
{
Console.WriteLine("Goodbye!");
}
When you run this (using dotnet run
):
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Enter Ctrl-C
and you should see:
^CGoodbye!
Because ASP.NET Core is for websites, you can do this with jQuery for example.