如何在 VsCode 中的 docker 中调试我的 Startup.cs(调试器附加得太晚了)

How to debug my Startup.cs within docker in VsCode (debugger is attached too late)

我设法使用 docker-compose 在 Ubuntu WSL-2 发行版(在 Windows 10)中调试 asp .net core 3.1 应用程序文件感谢这个 Vs code tutorial

但是考虑到我们使用 docker-compose up 命令启动容器,然后我们附加调试器,在 Program.csStartup.cs 中设置的所有断点都不会命中。事实上,当我手动附加调试器时,应用程序已经处理了这些文件,为时已晚。 所有其他断点(在控制器或后台进程中......)都被正确击中。

使用 Visual Studio 2019 Community 调试同一个项目时,我的所有断点都被命中,即使是 Program.csStartup.cs 中的断点,这是此处的预期行为。

我做错了什么?

永远不会命中断点 l.44

version: '3.7'

services:
  myapp:
    image: myapp
    container_name: myapp
    build:
      context: .
      dockerfile: src/MyApp/src/Dockerfile
    ports:
      - "60713:80"
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    volumes:
      - ~/.vsdbg:/remote_debugger:rw
networks:
    default:
      external:
         name: mynetwork
{
   "version": "0.2.0",
   "configurations": [
       {
           "name": "Docker .NET Core Attach (Preview)",
           "containerName": "myapp",
           "type": "docker",
           "request": "attach",
           "platform": "netCore",
           "sourceFileMap": {
               "/src": "${workspaceFolder}"
           }
       }
]
}

确实,如果我在容器启动之前启动 VS 代码调试器,我会收到以下错误消息

Error: Process 'docker exec -i "myapp...' exited with code 1
Error: Error: No such container: myapp

我打开了一个 Issue on Github 并在此处提供了回复:

  1. 来自布兰登滑铁卢 [MSFT]

Right now our only supported story for that is to launch it manually and then attach. We have an issue to add "real" compose debugging (microsoft/vscode-docker#840) ...

  1. 来自 Gregg Miskelly

... the only way to debug startup code is to add something like: while (!Debugger.IsAttached) { Thread.Sleep(100); } to the beginning of your startup code so that it will not proceed until a debugger is attached

总而言之,在 Microsoft 在 VSCode 上或通过临时扩展提供解决方案之前,一种解决方案是添加一些等待代码:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development)
    {
        while (!Debugger.IsAttached) { Thread.Sleep(100); }
    }  

现在 Startup.cs 中的断点已正确命中