Application Close Event – .NET 6

Does anyone know how to get something to hit off when a .net core 6 website is closed or when a user closes the website down, 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.

Update from comment, more explanation:

I would like to know both, for instance I would like to know how to make it so it updates the users status to offline when the application is closed and when the user closes the website down. I thought about hititng off something when the users session is expired as I am using CookieAuthentication but 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

>Solution :

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

Leave a Reply