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

Cla*_*doo 4 docker docker-compose visual-studio-code asp.net-core wsl-2

感谢此Vs code 教程,我成功地使用 docker-compose 文件在 Ubuntu WSL-2 发行版(在 Windows 10 上)中调试了 asp .net core 3.1 应用程序

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

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

我究竟做错了什么 ?

从未命中断点 l.44 从未命中断点 l.44

  • docker-compose.debug.yml(由 启动docker-compose -f "docker-compose.debug.yml" up -d --build
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
Run Code Online (Sandbox Code Playgroud)
  • 启动.json
{
   "version": "0.2.0",
   "configurations": [
       {
           "name": "Docker .NET Core Attach (Preview)",
           "containerName": "myapp",
           "type": "docker",
           "request": "attach",
           "platform": "netCore",
           "sourceFileMap": {
               "/src": "${workspaceFolder}"
           }
       }
]
}
Run Code Online (Sandbox Code Playgroud)

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

Error: Process 'docker exec -i "myapp...' exited with code 1
Error: Error: No such container: myapp
Run Code Online (Sandbox Code Playgroud)

Cla*_*doo 6

I opened an Issue on Github and here the provided responses:

  1. From Brandon Waterloo [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. From 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

So to conclude, until a solution is provided by Microsoft on VSCode or via an adhoc extension, one solution is to add some waiting code :

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

现在断点Startup.cs被正确击中 在此输入图像描述