Debugging ASP.NET Core applications in Visual Studio Code is a streamlined process primarily driven by the C# extension and a carefully configured launch.json
file. This setup allows you to efficiently pause execution, inspect variables, and step through your code to identify and resolve issues.
Essential Prerequisites
Before you begin debugging, ensure you have the necessary tools installed:
- .NET SDK: This includes the .NET runtime and command-line tools required to build, run, and debug ASP.NET Core applications.
- Visual Studio Code: The lightweight, yet powerful, source code editor.
- C# Extension for VS Code: Developed by Microsoft, this extension provides crucial C# language support, IntelliSense, and integrated debugging capabilities essential for .NET Core development.
Setting Up Your Debugging Environment
The cornerstone of debugging in VS Code is the launch.json
file, which dictates how the debugger should start your application.
- Open Your ASP.NET Core Project: Start by opening your project folder in Visual Studio Code.
- Access the Run & Debug View:
- On the left-hand Activity Bar, locate and click the Run & Debug icon (it resembles a play button with a bug). This action will open the Run and Debug view.
- Create
launch.json
:- If a
launch.json
file doesn't already exist in your project's.vscode
folder, you will see a prominent prompt. Click the 'create a launch.json file' link. - VS Code will then ask you to select an environment. From the options, select the suggested '.NET 5+ and .NET Core'.
- This action automatically generates a default
launch.json
file within a new or existing.vscode
directory in your project's root. This file contains default configurations tailored for launching and attaching to .NET applications.
- If a
Understanding launch.json
The generated launch.json
typically includes configurations for various debugging scenarios. For ASP.NET Core web applications, the most common configuration is named "Launch an ASP.NET Core Web App".
Example launch.json
(simplified relevant parts):
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch an ASP.NET Core Web App",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/<target-framework>/<your-project-name>.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)",
"uriFormat": "%s"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
// ... other possible configurations for console apps or attaching
]
}
Key properties within the configuration:
name
: The display name for this debug configuration in the Run & Debug view.type
: Specifies the debugger to use (e.g.,coreclr
for .NET Core).request
: Defines the type of debug session (launch
to start a new process,attach
to connect to an existing one).preLaunchTask
: Often set tobuild
, this executes a task (defined intasks.json
) likedotnet build
before debugging starts, ensuring your code is compiled.program
: The absolute path to your application's compiled DLL. Make sure<target-framework>
(e.g.,net8.0
) and<your-project-name>
match your project.serverReadyAction
: Particularly useful for web apps, this action automatically opens a web browser to the application's URL once the server indicates it's ready.
The Debugging Process in Action
With your launch.json
configured, you're ready to debug your ASP.NET Core application.
-
Set Breakpoints:
- Open any C# source file (e.g.,
Program.cs
, a controller, or a service). - Click in the gutter to the left of the line number where you want the program execution to pause. A red dot will appear, indicating an active breakpoint.
- Tip: Right-click on a breakpoint to set a conditional breakpoint (pauses only if a specified condition is true) or a log point (logs a message to the Debug Console without pausing execution).
- Open any C# source file (e.g.,
-
Start Debugging:
- Return to the Run & Debug view (Ctrl+Shift+D or the icon).
- From the dropdown menu at the top, select your desired launch configuration (e.g., "Launch an ASP.NET Core Web App").
- Click the green Start Debugging button (the play icon) next to the dropdown, or simply press
F5
. - Your application will compile (if
preLaunchTask
is set) and then launch in debug mode. If it's a web application, a browser window should automatically open to your application's URL.
-
Interact with the Debugger:
- When your application's execution hits a breakpoint, it will pause, and the corresponding line of code will be highlighted.
- The VARIABLES section in the Run & Debug view displays the current values of local variables and arguments within the current scope.
- The WATCH section allows you to manually add and monitor specific expressions or variables.
- The CALL STACK shows the sequence of function calls that led to the current execution point.
- The BREAKPOINTS section lists all active breakpoints and allows you to toggle or remove them.
Debugger Control Actions
Use the following controls, available in the floating debug toolbar or via keyboard shortcuts, to navigate through your code during a debugging session:
Action | Icon | Keyboard Shortcut | Description |
---|---|---|---|
Continue | ▶️ | F5 |
Resumes program execution until the next breakpoint or the program terminates. |
Step Over | ⏭️ | F10 |
Executes the current line and moves to the next, stepping over function calls. |
Step Into | ⬇️ | F11 |
Executes the current line and steps into a function call if one is present. |
Step Out | ⤴️ | Shift+F11 |
Executes the remainder of the current function and pauses at its return. |
Restart | 🔄 | Ctrl+Shift+F5 |
Stops the current debugging session and starts a new one. |
Stop | ⏹️ | Shift+F5 |
Terminates the active debugging session. |
Using the Debug Console
The Debug Console (located in the bottom panel of VS Code) is a powerful tool during debugging:
- It displays output from your application (e.g., messages from
Console.WriteLine
orILogger
). - While execution is paused at a breakpoint, you can use the Debug Console to evaluate expressions, inspect variable values, and even modify variables in real-time (e.g.,
myVariable
to see its value, ormyVariable = "new value"
to change it).
Tips for Effective ASP.NET Core Debugging
- Logging is Your Friend: Integrate robust logging (
ILogger
in ASP.NET Core) throughout your application. Logs provide valuable context, especially for issues in asynchronous operations or when direct debugging isn't feasible. tasks.json
Verification: ThepreLaunchTask
inlaunch.json
relies on tasks defined intasks.json
(also in the.vscode
folder). Ensure yourtasks.json
correctly defines build commands (e.g.,dotnet build
) for your project.- Environment Variables: Leverage the
env
property inlaunch.json
to control environment-specific settings, such asASPNETCORE_ENVIRONMENT
set toDevelopment
, which can influence error reporting and configuration loading. - Hot Reload: For rapid iteration on UI changes or small code modifications, ASP.NET Core's Hot Reload feature can update your running application without needing a full restart of the debugger.
By understanding and utilizing these steps and tools, you can effectively debug your ASP.NET Core applications within Visual Studio Code, leading to more efficient issue resolution and a smoother development workflow.