Blazor Visual Studio Code



  1. Blazor Visual Studio Code
  2. Blazor Visual Studio Code

This is a companion extension to the C# extension that brings some improvements to the experience for debugging Blazor WebAssembly in VS Code. This extension should not be installed by itself and will automatically install the C# extension. For more information on Blazor, visit the Blazor homepage. The Syncfusion Essential Studio Blazor extension for Visual Studio Code allows you to create a Blazor project using pre-built templates. Learn how to set up your development environment and build your first WebAssembly app with Blazor, Visual Studio Code, and C#. Learning objectives In this module, you will: Configure your local environment for Blazor development with Visual Studio Code. The following steps illustrate how to download and install the Syncfusion Blazor Template Studio with the Code Generator extension from the Visual Studio Marketplace. Note: Syncfusion Blazor Code Generator was shipped within the Syncfusion Template Studio. Download the Syncfusion Blazor Template Studio from the Visual Studio Marketplace.

In this article, we are going to learn about Azure Static Web Apps, which is a great solution for publishing static web applications into the cloud.

We’ll start by looking at what an Azure Static Web App is. Then we’ll learn how to build a Blazor WebAssembly Application that talks with a Serverless Function API in the back-end. After that, we’ll see how to create an Azure Static Web App from the portal. Along with that, we’ll also learn configuring GitHub Actions Workflow for integrating the Azure Static Web App with the repository. Finally, we’ll test our Azure Static Web Apps to make sure that everything works as expected.

To read more about Azure, you can visit our Azure with ASP.NET Core page, where you can find all the articles from the series.

We have divided this article into the following sections:

Let’s start.

Introduction to Azure Static Web Apps

Blazor Visual Studio Code

We can use Azure Static Web Apps to build and publish a static web application from a GitHub repository into Azure. By serving pre-rendered files from the cloud without the need of provisioning any web servers, they provide an excellent way for hosting static files like HTML, JavaScript, etc inside Azure. Of course, Azure takes care of aspects like server maintenance, scaling, content distribution, etc and we can just focus on our application without having to worry about any of those.

Azure Static Web Apps supports all major JavaScript and TypeScript based modern front-end apps including those developed with frameworks like Angular, React, Vue.js, etc. Additionally, It supports ASP.NET Core Blazor apps as well. With Static Web Apps, we can even build a back-end for our Blazor application using serverless Function API which is an added advantage.

In our Deploying ASP.NET Core Web API to Azure API Apps article, we learned how to deploy an ASP.NET Core with Angular Client App into Azure. However, If we want to deploy pure Javascript/Typescript apps like the Angular CLI apps or React apps, Azure Static Web Apps is the best choice out there right now.

In this tutorial, we are going to learn how to create an ASP.NET Core Blazor WebAssembly application that talks with a Serverless Function API in the back-end. After that, we’ll see how to deploy it to Azure Static Web apps as well. We are going to accomplish this by connecting a GitHub repository to the Static Web Apps in Azure Portal. This will configure the GitHub repository for Continuous Delivery and provide a seamless experience for building and publishing our Blazor application.

Configuring the Blazor Starter Application

The first step is creating and configuring a Blazor WebAssembly application. We have covered Blazor WebAssembly in detail in our Blazor WebAssembly Series. The process of creating web applications using Blazor WebAssembly is explained very well in that series. However, in this example, we are going to take a different approach by making use of a Blazor starter template for creating our project.

Blazor Starter Application Template is an excellent choice for creating a Static Web App project with Blazor. This starter kit will help us to quickly create a solution with a Blazor project. The template contains a Blazor WebAssembly client application, a serverless Function API back-end, and a C# class library that can contain code that is shared between the Client App and the API.

Creating the Project

Let’s start by creating the project. For that, first, we need to log into GitHub and navigate to the blazor-starter repository. Then we can proceed to create a new GitHub repository using that template by clicking on the Use this template button:

After that, on the next screen, we can generate the repository by clicking on the Create repository from template button after specifying a Repository Name:

Once the repository is created, we are going to clone it locally and analyze the source code.

Cloning the GitHub project

For cloning the project locally, from the GitHub repository, first, we need to click on the Code dropdown and then on the Copy button in the HTTPS tab:

Then, we can open Visual Studio and choose Clone a repository option.

After that, we need to provide the copied Git repository URL and a local folder path for the project in the Clone a repository screen and click on the Clone button:


This will clone the GitHub project into our local system. Without further ado, let’s inspect the source code of the project that we just created.

Inspecting the Project

Now let’s open the solution in Visual Studio and inspect the project structure. We can see that there are three projects inside the solution:

  1. Client: This is the Blazor WebAssembly client application that fetches data from the API
  2. API: The API project is a C# Azure Functions App. We have explained Azure Functions in detail in our Creating Serverless Apps using Azure Functions article. The Blazor client application will get data from this back-end API. Currently, Azure Static Web Apps supports only Functions in the back-end
  3. Shared: This is a C# class library that is shared between the Blazor client and Functions API. This is a good place to put any code that is shared between the Client App and API

Now that we have analyzed the solution, let’s go ahead and test it locally.

Testing the Project Locally

To run the app locally, we have to start both the API and Client projects. For setting multiple startup projects, we can select the Multiple startup projects option in the Startup Project property of the Visual Studio solution, and inside that, we can choose to start both the API and Client project:

This will ensure that both projects will start when we run the solution. After running the solution, let’s navigate to the Fetch data page:

The Fetch data page in the app gets the weather forecast data from the backend Function API and displays it on the page.

Cool!

We have tested our Blazor Starter App locally. Without any further delay, let’s proceed to deploy it to Azure.

Creating Azure Static Web Apps

For deploying our Blazor application to Azure, first, we need to create an Azure Static Web App from the Azure Portal:

Blazor server visual studio code

Please note that at the time of writing this article, Azure Static Web Apps is in Public Preview which means it can be used free of cost. Microsoft is planning to release this into General Availability(GA) soon and hopefully, they’ll announce the pricing details along with that. However, the serverless APIs that we implement using Azure Functions will incur a cost depending on the consumption plan that we choose. We have explained creating serverless applications using Azure Functions in our Creating Serverless Apps using Azure Functions article.

Once we click on the Create button, It will take us to the Create Static Web App screen where we need to provide some information about the App:

  1. First, we need to select a Subscription.
  2. Then, we need to either choose an existing Resource Group or create a new one.
  3. After that, we need to provide a Name for our App.
  4. Finally, we need to choose a Region.

After providing this information, we have to link our app with a GitHub account by clicking on the Sign in with GitHub button. We have learned how to link our GitHub account with Azure in the Continuous Deployment from GitHub to Azure App Service article. The same steps apply here as well.

Configuring the GitHub Actions Workflow

Once we sign into our GitHub account and Authorize it, we need to configure the Source Control and Build details:

  1. First, we need to provide the Source Control Details like Organization, Repository, and Branch.
  2. Then, we need to provide Build Details. We can choose the Build Presets as Blazor and leave the default values for the rest of the fields. Since we are using the Blazor starter template, it will automatically identify our Client App and API locations. Perfect!
  3. After that, we can click on the Review + Create button.

This will initiate the validation process and once that step is completed, we can finish the App creation process by clicking on the Create button. This process could take a few minutes to complete and we can view the progress in the portal.

Examining Azure Static Web Apps in Portal

Once the Azure Static Web App is created, the linked GitHub repository will trigger a CI/CD from its Action Workflow. Let’s wait till that process is completed.

On completion of the deployment, we can see the GitHub Action runs link in the Deployment History. Also, note that there is a Functions section that will list the API Functions that we created as part of the solution:

Clicking on the GitHub Action runs link will take us to the Actions section of the linked GitHub repository:

Here we can see the details of CI/CD pipelines that the GitHub Actions Workflow triggered.

On navigating to the Functions section of the Azure Static Web App, we can see the serverless API functions that we implemented as part of the solution:

Great!

Blazor

Now that we have completed examining the Azure Static Web App, let’s proceed to test it.

Testing Azure Static Web Apps

For testing the Azure Static Web App, we just need to navigate to its URL. Interestingly, unlike the App Services and Function Apps, the URL of Static Web Apps doesn’t contain the app name that we provided and instead has some random values. This could be because the Azure Static Web App is still in preview. After navigating to the application, let’s check the Fetch Data page:

We can see that the Fetch Data page retrieves data from our serverless API Function and displays it on the page.

Excellent!

We have tested the Azure Static Web App that we had just created. Now let’s take a step back and look at the architecture to understand the big picture.

Let’s take a look at a diagram that represents deployment architecture for our scenario:

Our Static Web Application code resides in a GitHub repository. The GitHub Actions Workflow triggers CI/CD into the Azure Static Web Apps. Azure Static Web App contains static files(Blazor WASM in our example) in the client-side and Function API in the back-end. Users can access the static Web App over the internet via a URL just like how they access any other applications hosted in Azure.

Conclusion

We have learned the following concepts as part of this article:

  • What an Azure Static Web App is
  • Building a Blazor Application with a serverless back-end using Blazor Starter Template
  • Testing a Blazor Application with serverless back-end locally
  • Creating Azure Static Web Apps from Portal
  • Configuring the GitHub Actions Workflow for Azure Static Web Apps
  • Testing the Azure Static Web Apps
-->

Blazor WebAssembly apps can be debugged using the browser dev tools in Chromium-based browsers (Edge/Chrome). You can also debug your app using the following integrated development environments (IDEs):

  • Visual Studio
  • Visual Studio for Mac
  • Visual Studio Code

Available scenarios include:

  • Set and remove breakpoints.
  • Run the app with debugging support in IDEs.
  • Single-step through the code.
  • Resume code execution with a keyboard shortcut in IDEs.
  • In the Locals window, observe the values of local variables.
  • See the call stack, including call chains between JavaScript and .NET.

For now, you can't:

  • Break on unhandled exceptions.
  • Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in Program.Main (Program.cs) and breakpoints in the OnInitialized{Async} lifecycle methods of components that are loaded by the first page requested from the app.
  • Debug in non-local scenarios (for example, Windows Subsystem for Linux (WSL) or Visual Studio Codespaces).
  • Automatically rebuild the backend *Server* app of a hosted Blazor WebAssembly solution during debugging, for example by running the app with dotnet watch run.

Prerequisites

Debugging requires either of the following browsers:

  • Google Chrome (version 70 or later) (default)
  • Microsoft Edge (version 80 or later)

Ensure that firewalls or proxies don't block communication with the debug proxy (NodeJS process). For more information, see the Firewall configuration section.

Visual Studio Code users require the following extensions:

  • Blazor WASM Debugging Extension (when using the C# for Visual Studio Code Extension version 1.23.9 or later)

After opening a project in VS Code, you may receive a notification that additional setup is required to enable debugging. If requested, install the required extensions from the Visual Studio Marketplace. To inspect the installed extensions, open View > Extensions from the menu bar or select the Extensions icon in the Activity sidebar.

Blazor Visual Studio Code

Visual Studio for Mac requires version 8.8 (build 1532) or later:

  1. Install the latest release of Visual Studio for Mac by selecting the Download Visual Studio for Mac button at Microsoft: Visual Studio for Mac.
  2. Select the Preview channel from within Visual Studio. For more information, see Install a preview version of Visual Studio for Mac.

Note

Apple Safari on macOS isn't currently supported.

Enable debugging

To enable debugging for an existing Blazor WebAssembly app, update the launchSettings.json file in the startup project to include the following inspectUri property in each launch profile:

Once updated, the launchSettings.json file should look similar to the following example:

The inspectUri property:

  • Enables the IDE to detect that the app is a Blazor WebAssembly app.
  • Instructs the script debugging infrastructure to connect to the browser through Blazor's debugging proxy.

The placeholder values for the WebSockets protocol (wsProtocol), host (url.hostname), port (url.port), and inspector URI on the launched browser (browserInspectUri) are provided by the framework.

To debug a Blazor WebAssembly app in Visual Studio:

  1. Create a new hosted Blazor WebAssembly solution.

  2. Press F5 to run the app in the debugger.

    Note

    Start Without Debugging (Ctrl+F5) isn't supported. When the app is run in Debug configuration, debugging overhead always results in a small performance reduction.

  3. In the *Client* app, set a breakpoint on the currentCount++; line in Pages/Counter.razor.

    Vermeer’s Paint Brushes. The quest begins with Vermeer wanting you to search for his paintbrushes and paint around the Luhau Pool, which is easy enough. He’ll hand you two paintings that you can use as a reference to locate the two items, but you don’t need that because we’ll tell you where the items are. Vermeer paintbrushes and paints.

  4. In the browser, navigate to Counter page and select the Click me button to hit the breakpoint.

  5. In Visual Studio, inspect the value of the currentCount field in the Locals window.

  6. Press F5 to continue execution.

While debugging a Blazor WebAssembly app, you can also debug server code:

  1. Set a breakpoint in the Pages/FetchData.razor page in OnInitializedAsync.
  2. Set a breakpoint in the WeatherForecastController in the Get action method.
  3. Browse to the Fetch Data page to hit the first breakpoint in the FetchData component just before it issues an HTTP request to the server.
  4. Press F5 to continue execution and then hit the breakpoint on the server in the WeatherForecastController.
  5. Press F5 again to let execution continue and see the weather forecast table rendered in the browser.

Note

Breakpoints are not hit during app startup before the debug proxy is running. This includes breakpoints in Program.Main (Program.cs) and breakpoints in the OnInitialized{Async} lifecycle methods of components that are loaded by the first page requested from the app.

If the app is hosted at a different app base path than /, update the following properties in Properties/launchSettings.json to reflect the app's base path:

  • applicationUrl:

  • inspectUri of each profile:

The placeholders in the preceding settings:

  • {INSECURE PORT}: The insecure port. A random value is provided by default, but a custom port is permitted.
  • {APP BASE PATH}: The app's base path.
  • {SECURE PORT}: The secure port. A random value is provided by default, but a custom port is permitted.
  • {PROFILE 1, 2, .. N}: Launch settings profiles. Usually, an app specifies more than one profile by default (for example, a profile for IIS Express and a project profile, which is used by Kestrel server).

In the following examples, the app is hosted at /OAT with an app base path configured in wwwroot/index.html as <base href='/OAT/'>:

For information on using a custom app base path for Blazor WebAssembly apps, see Host and deploy ASP.NET Core Blazor.

Debug standalone Blazor WebAssembly

Blazor Visual Studio Code

For information on configuring VS Code assets in the .vscode folder, see the Linux operating system guidance in Tooling for ASP.NET Core Blazor.

  1. Open the standalone Blazor WebAssembly app in VS Code.

    You may receive a notification that additional setup is required to enable debugging:

    Additional setup is required to debug Blazor WebAssembly applications.

    If you receive the notification:

    • Confirm that the latest C# for Visual Studio Code Extension is installed. To inspect the installed extensions, open View > Extensions from the menu bar or select the Extensions icon in the Activity sidebar.
    • When using the C# for Visual Studio Code Extensionversion 1.23.9 or later, confirm that the latest Blazor WASM Debugging Extension is installed. To inspect the installed extensions, open View > Extensions from the menu bar or select the Extensions icon in the Activity sidebar.
    • Confirm that JavaScript preview debugging is enabled. Open the settings from the menu bar (File > Preferences > Settings). Search using the keywords debug preview. In the search results, set or confirm that the check box for Debug > JavaScript: Use Preview is checked. If the option to enable preview debugging isn't present, either upgrade to the latest version of VS Code or install the JavaScript Debugger Extension (VS Code versions 1.46 or earlier).
    • Reload the window.
  2. Start debugging using the F5 keyboard shortcut or the menu item.

    Note

    Start Without Debugging (Ctrl+F5) isn't supported. When the app is run in Debug configuration, debugging overhead always results in a small performance reduction.

  3. When prompted, select the Blazor WebAssembly Debug option to start debugging.

  4. The standalone app is launched, and a debugging browser is opened.

  5. In the *Client* app, set a breakpoint on the currentCount++; line in Pages/Counter.razor.

  6. In the browser, navigate to Counter page and select the Click me button to hit the breakpoint.

Note

Breakpoints are not hit during app startup before the debug proxy is running. This includes breakpoints in Program.Main (Program.cs) and breakpoints in the OnInitialized{Async} lifecycle methods of components that are loaded by the first page requested from the app.

Debug hosted Blazor WebAssembly

  1. Open the Client project folder of the hosted Blazor solution folder in VS Code.

  2. If there's no launch configuration set for the project, the following notification appears. Select Yes.

    Required assets to build and debug are missing from '{APPLICATION NAME}'. Add them?

    For information on configuring VS Code assets in the .vscode folder, see the Linux operating system guidance in Tooling for ASP.NET Core Blazor.

  3. In the command palette at the top of the window, select the Server project within the hosted solution.

A launch.json file is generated with the launch configuration for launching the debugger.

Attach to an existing debugging session

To attach to a running Blazor app, create a launch.json file with the following configuration:

Note

Attaching to a debugging session is only supported for standalone apps. To use full-stack debugging, you must launch the app from VS Code.

Launch configuration options

The following launch configuration options are supported for the blazorwasm debug type (.vscode/launch.json).

OptionDescription
requestUse launch to launch and attach a debugging session to a Blazor WebAssembly app or attach to attach a debugging session to an already-running app.
urlThe URL to open in the browser when debugging. Defaults to https://localhost:5001.
browserThe browser to launch for the debugging session. Set to edge or chrome. Defaults to chrome.
traceUsed to generate logs from the JS debugger. Set to true to generate logs.
hostedMust be set to true if launching and debugging a hosted Blazor WebAssembly app.
webRootSpecifies the absolute path of the web server. Should be set if an app is served from a sub-route.
timeoutThe number of milliseconds to wait for the debugging session to attach. Defaults to 30,000 milliseconds (30 seconds).
programA reference to the executable to run the server of the hosted app. Must be set if hosted is true.
cwdThe working directory to launch the app under. Must be set if hosted is true.
envThe environment variables to provide to the launched process. Only applicable if hosted is set to true.

Example launch configurations

Launch and debug a standalone Blazor WebAssembly app

Attach to a running app at a specified URL

Launch and debug a hosted Blazor WebAssembly app with Microsoft Edge

Browser configuration defaults to Google Chrome. When using Microsoft Edge for debugging, set browser to edge. To use Google Chrome, either don't set the browser option or set the option's value to chrome.

In the preceding example, MyHostedApp.Server.dll is the Server app's assembly. The .vscode folder is located in the solution's folder next to the Client, Server, and Shared folders.

To debug a Blazor WebAssembly app in Visual Studio for Mac:

  1. Create a new ASP.NET Core hosted Blazor WebAssembly app.

  2. Press + to run the app in the debugger.

    Note

    Start Without Debugging (++) isn't supported. When the app is run in Debug configuration, debugging overhead always results in a small performance reduction.

    Important

    Google Chrome or Microsoft Edge must be the selected browser for the debugging session.

  3. In the *Client* app, set a breakpoint on the currentCount++; line in Pages/Counter.razor.

  4. In the browser, navigate to Counter page and select the Click me button to hit the breakpoint:

  5. In Visual Studio, inspect the value of the currentCount field in the Locals window.

  6. Press + to continue execution.

While debugging a Blazor WebAssembly app, you can also debug server code:

  1. Set a breakpoint in the Pages/FetchData.razor page in OnInitializedAsync.
  2. Set a breakpoint in the WeatherForecastController in the Get action method.
  3. Browse to the Fetch Data page to hit the first breakpoint in the FetchData component just before it issues an HTTP request to the server.
  4. Press + to continue execution and then hit the breakpoint on the server in the WeatherForecastController.
  5. Press + again to let execution continue and see the weather forecast table rendered in the browser.

Note

Breakpoints are not hit during app startup before the debug proxy is running. This includes breakpoints in Program.Main (Program.cs) and breakpoints in the OnInitialized{Async} lifecycle methods of components that are loaded by the first page requested from the app.

For more information, see Debugging with Visual Studio for Mac.

Debug in the browser

The guidance in this section applies to Google Chrome and Microsoft Edge running on Windows.

  1. Run a Debug build of the app in the Development environment.

  2. Launch a browser and navigate to the app's URL (for example, https://localhost:5001).

  3. In the browser, attempt to commence remote debugging by pressing Shift+Alt+d.

    The browser must be running with remote debugging enabled, which isn't the default. If remote debugging is disabled, an Unable to find debuggable browser tab error page is rendered with instructions for launching the browser with the debugging port open. Follow the instructions for your browser, which opens a new browser window. Close the previous browser window.

  1. Once the browser is running with remote debugging enabled, the debugging keyboard shortcut in the previous step opens a new debugger tab.

  2. After a moment, the Sources tab shows a list of the app's .NET assemblies within the file:// node.

  3. In component code (.razor files) and C# code files (.cs), breakpoints that you set are hit when code executes. After a breakpoint is hit, single-step (F10) through the code or resume (F8) code execution normally.

Blazor provides a debugging proxy that implements the Chrome DevTools Protocol and augments the protocol with .NET-specific information. When debugging keyboard shortcut is pressed, Blazor points the Chrome DevTools at the proxy. The proxy connects to the browser window you're seeking to debug (hence the need to enable remote debugging).

Browser source maps

Browser source maps allow the browser to map compiled files back to their original source files and are commonly used for client-side debugging. However, Blazor doesn't currently map C# directly to JavaScript/WASM. Instead, Blazor does IL interpretation within the browser, so source maps aren't relevant.

Firewall configuration

If a firewall blocks communication with the debug proxy, create a firewall exception rule that permits communication between the browser and the NodeJS process.

Warning

Modification of a firewall configuration must be made with care to avoid creating security vulnerablities. Carefully apply security guidance, follow best security practices, and respect warnings issued by the firewall's manufacturer.

Permitting open communication with the NodeJS process:

  • Opens up the Node server to any connection, depending on the firewall's capabilities and configuration.
  • Might be risky depending on your network.
  • Is only recommended on developer machines.

If possible, only allow open communication with the NodeJS process on trusted or private networks.

For Windows Firewall configuration guidance, see Create an Inbound Program or Service Rule. For more information, see Windows Defender Firewall with Advanced Security and related articles in the Windows Firewall documentation set.

Troubleshoot

If you're running into errors, the following tips may help:

  • In the Debugger tab, open the developer tools in your browser. In the console, execute localStorage.clear() to remove any breakpoints.
  • Confirm that you've installed and trusted the ASP.NET Core HTTPS development certificate. For more information, see Enforce HTTPS in ASP.NET Core.
  • Visual Studio requires the Enable JavaScript debugging for ASP.NET (Chrome, Edge and IE) option in Tools > Options > Debugging > General. This is the default setting for Visual Studio. If debugging isn't working, confirm that the option is selected.
  • If your environment uses an HTTP proxy, make sure that localhost is included in the proxy bypass settings. This can be done by setting the NO_PROXY environment variable in either:
    • The launchSettings.json file for the project.
    • At the user or system environment variables level for it to apply to all apps. When using an environment variable, restart Visual Studio for the change to take effect.
  • Ensure that firewalls or proxies don't block communication with the debug proxy (NodeJS process). For more information, see the Firewall configuration section.

Breakpoints in OnInitialized{Async} not hit

The Blazor framework's debugging proxy takes a short time to launch, so breakpoints in the OnInitialized{Async} lifecycle methods might not be hit. We recommend adding a delay at the start of the method body to give the debug proxy some time to launch before the breakpoint is hit. You can include the delay based on an if compiler directive to ensure that the delay isn't present for a release build of the app.

OnInitialized:

OnInitializedAsync:

Visual Studio (Windows) timeout

If Visual Studio throws an exception that the debug adapter failed to launch mentioning that the timeout was reached, you can adjust the timeout with a Registry setting:

Blazor

The {TIMEOUT} placeholder in the preceding command is in milliseconds. For example, one minute is assigned as 60000.