Search code examples
c#debuggingblazorblazor-webassemblywebassembly

Blazor WASM - How to debug the Program.cs (VS2022 or JB Rider)?


I have been struggling for a while using Blazor WASM on .Net Core 6.0 (Stand-alone and Hosted) to debug my program.cs file without success.

As Microsoft mentioned, we can debug the app using the Chromium option to debug the app on the Browser (Google or Edge)... but still the debug is clunky and doesn't work as expected.

Is there any other alternative to debug my C# code on Visual Studio 2022 or JetBrains Ryder IDEs?

References

https://learn.microsoft.com/en-us/aspnet/core/blazor/debug?view=aspnetcore-6.0&tabs=visual-studio

Understanding Blazor Assembly with ASP.net Core Hosted Model


Solution

  • There is an option to debug Blazor C# code (Even the program.cs file) without too much effort... so far it works pretty well for me.

    The workaround works for VS 2022 or JetBrains Rider...

    Steps

    1. Open your IDE
    2. Open the Terminal console CTRL+`
    3. Use the dotnet CLI to watch your project: dotnet.exe watch --project ./PROJECT_PATH/PROJECT.csproj CLI
    4. Then, go to Attach to process option in your IDE and attach the process that is currently running...
      • Visual Studio 2022: Menu > Debug > Attach to Process VS2022 config
      • JetBrains Rider: Menu > Run > Attach to Process Rider Config
    5. Then you should be able to debug, put breakpoints, watch your variables and whatever you need from there...

    ...now, with that you don't will be able to put a breakpoint in your Program.cs... because while you are doing the previous steps, the app will be up and running...

    Then... just include the following lines at the beginning of the Program.cs file.

    Console.WriteLine("Attach your process into your IDE...");
    
    // Wait 20 seconds to the developer attach the process for debugging
    for (int i = 0; i < 20; i++)
        Thread.Sleep(1000);
    
    Console.WriteLine("Start Program.cs");
    

    This will give you enough time to run the application and attach the process to your IDE... and from there you should be able to debug your program and check configs, Dependency Injection and services stuff.

    So, at the end you just add some buffer time that gives you enough time to attach the process to your IDE and be able to be debugged.

    Results

    Results