-2

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.

Tseng
  • 61,549
  • 15
  • 193
  • 205
Student222
  • 3,021
  • 2
  • 19
  • 24
  • asp.net is for web apps.. did you mean a .net core console app? – Matt Johnson-Pint Dec 22 '16 at 19:48
  • 1
    It is not at all clear what you're wanting to do or why. Please provide more detail. –  Dec 22 '16 at 19:49
  • 2
    You cannot achive this with `Asp.NET Core` or with any other `Asp.NET` frameworks. `Control - C` is obviosly keyboard input. So you need to achive this on client side - javascript maybe – Fabio Dec 22 '16 at 19:50
  • @Fabio, I don't mean Ctrl-C(Copy) at client side, but Ctrl-C at server side to interrupt the process. Is there a way to listen for that? – Student222 Dec 22 '16 at 20:03

2 Answers2

4

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!
omajid
  • 14,165
  • 4
  • 47
  • 64
-3

Because ASP.NET Core is for websites, you can do this with jQuery for example.

See: How to detect Ctrl+V, Ctrl+C using JavaScript?

Community
  • 1
  • 1
yooouuri
  • 2,578
  • 10
  • 32
  • 54