Home > Back-end >  How do I register code to run when shutting down an ASP.NET web application using the new .NET 6 for
How do I register code to run when shutting down an ASP.NET web application using the new .NET 6 for

Time:05-03

Does anyone know how to get something to hit off when a .NET Core 6 website is closed? I've looked online and I keep seeing Startup.cs explanation but with the new .NET Core 6 this was removed and all we have is Program.cs now.

I'm trying to run a database script when the application is closed to update all the users to offline otherwise when the application is closed all the users stay online because the users haven't been able to 'Logout' to run a database script to update their status to offline.

CodePudding user response:

In your startup you can use the injected IHostApplicationLifetime for that (docs). For example:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime hostApplicationLifetime, TelemetryClient telemetryClient)
        {
            hostApplicationLifetime.ApplicationStarted.Register(() => { telemetryClient.TrackEvent("App Started"); });
            hostApplicationLifetime.ApplicationStopping.Register(() => { telemetryClient.TrackEvent("App Stopping"); });
            hostApplicationLifetime.ApplicationStopped.Register(() => {
                telemetryClient.TrackEvent("App Stopped");
                telemetryClient.Flush();

                Thread.Sleep(TimeSpan.FromSeconds(5));
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.UseMiddleware<CustomMiddleware>();
        }

For .Net 6 see this code example

  • Related