【发布时间】:2020-11-23 14:54:23
【问题描述】:
我看到了几篇关于 IApplicationLifetime 以及在应用程序启动和停止时触发执行的方式的文章,但我可能错过了一些东西,因为它只是没有被触发。 这是我的解决方法: 我打开了一个项目模板Container Application for kubernetes, asp.net core 2.2
Program.cs 看起来与创建时一样:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Kubernetes1
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Startup.cs 如下所示:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Kubernetes1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping called"));
appLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped called"));
app.Run(async (context) =>
{
Console.WriteLine("AAA");
});
}
}
}
我在这里要做的就是在 cmd 中运行应用程序,然后停止它并在控制台中看到 2 行打印:
- ApplicationStopping 已调用
- ApplicationStopped 调用 我没能做到。 有什么想法吗?
【问题讨论】:
-
检查输出时如何停止程序?
-
在另一个 cmd 窗口中我输入:
Get-Process -Name *dotnet* | Stop-Process -
在同一窗口中尝试
cntrl+c。 -
谢谢!确实是问题所在。不知道停止过程不是优雅的停止
标签: c# asp.net-core asp.net-core-middleware