在关闭使用新的 .NET 6 格式的 ASP.NET Web 应用程序时,如何将代码注册到 运行?

How do I register code to run when shutting down an ASP.NET web application using the new .NET 6 format?

有谁知道如何在 .NET Core 6 网站关闭时触发某些内容?我在网上看过,我一直看到 Startup.cs 的解释,但是在新的 .NET Core 6 中,它被删除了,我们现在只有 Program.cs

我正在尝试 运行 一个数据库脚本,当应用程序关闭时将所有用户更新为离线,否则当应用程序关闭时所有用户都保持在线,因为用户无法'Logout' 到 运行 用于将其状态更新为离线的数据库脚本。

在您的启动中,您可以为此使用注入的 IHostApplicationLifetime (docs)。例如:

// 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>();
        }

对于 .Net 6,请参阅 this code example