c# - 在 ASP.NET Core Web API 应用程序中禁用 Ctrl+C 关闭
问题描述
我正在尝试为在 ASP.NET Core Web 应用程序中创建的 API 主机禁用自动启用的“Ctrl+C”关闭。以前在这里问过同样的问题,但是使用下面的代码对我不起作用——启动时仍然显示“按 Ctrl+C”消息,实际上,按 Ctrl+C 会停止应用程序。
如何关闭此行为?
添加 Console.CancelKeyPress 处理程序以捕获 Ctrl-C 不起作用 - 设置 'Cancel = True' 不会阻止 ASP.NET 主机看到 Ctrl-C 并停止。
这是代码:
public static void Main(string[] args) {
var tokenSource = new CancellationTokenSource();
var task = CreateHostBuilder(args).Build().RunAsync(tokenSource.Token);
while (!task.IsCompleted) {
// TODO: Other stuff...
Thread.Sleep(1000);
};
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
这是应用程序启动时的输出(请注意,“Press Ctrl+C...”消息仍然存在):
info: Microsoft.Hosting.Lifetime[0] Now listening on: https://localhost:5001 info: Microsoft.Hosting.Lifetime[0] Now listening on: http://localhost:5000 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: <path>
解决方案
ASP.NET Core 有一个主机生命周期的概念来管理应用程序的生命周期。
有几个实现,例如
ConsoleLifetime
,它监听Ctrl+C
或SIGTERM
启动关机。SystemdLifetime
,通知systemd
服务启动和停止WindowsServiceLifetime
,与 Windows 服务集成
我们将插入我们自己的实现,它将监听Ctrl+C
键,并取消它以防止它停止应用程序:
public class NoopConsoleLifetime : IHostLifetime, IDisposable
{
private readonly ILogger<NoopConsoleLifetime> _logger;
public NoopConsoleLifetime(ILogger<NoopConsoleLifetime> logger)
{
_logger = logger;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task WaitForStartAsync(CancellationToken cancellationToken)
{
Console.CancelKeyPress += OnCancelKeyPressed;
return Task.CompletedTask;
}
private void OnCancelKeyPressed(object? sender, ConsoleCancelEventArgs e)
{
_logger.LogInformation("Ctrl+C has been pressed, ignoring.");
e.Cancel = true;
}
public void Dispose()
{
Console.CancelKeyPress -= OnCancelKeyPressed;
}
}
然后向 DI 注册:
services.AddSingleton<IHostLifetime, NoopConsoleLifetime>();
当您启动应用程序时,您将无法使用 Ctrl+C 停止它:
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Demo.NoopConsoleLifetime[0]
Ctrl+C has been pressed, ignoring.
info: Demo.NoopConsoleLifetime[0]
Ctrl+C has been pressed, ignoring.
参考
推荐阅读
- javascript - javascript中的条件字符串检查
- apache-nifi - Nifi:MergeRecord 不会等待并将 json 文件分组为一批
- linq - 在使用 Linq 选择的匿名对象中等待任务
- maven - 将 Azure Devops 工件发布到 Maven Central
- php - 如何为 Xdebug 3.0 版设置 VSCode launch.json?
- r - 如何从 renv.lock 更改 R 存储库 CRAN 以从内部/企业存储库获取包?
- ruby-on-rails - 尝试测试调用 AWS S3 Bucket copy_to 的 (minitest) 方法。如何模拟或存根?
- r - 当我们有依赖于输入的动态 UI 时,如何在 R 中获得输出?
- list - 试图输出一个列表,但得到一个值
- python - 在真实设备上的 Python 脚本上使用 Selenium 测量页面加载速度