Getting Started with Blazor WebAssembly on .NET Core 3.1

On 19th of May 2020, Blazor WebAssembly 3.2.0 was released by Microsoft, which is the fully-featured and supported release of Blazor WebAssembly that is ready for production use.

What is Blazor?, you might ask. Let me give you a straight forward answer to that. As advertised, Blazor is an open source and cross-platform web UI framework for building single-page apps(SPAs) using .NET and C# instead of JavaScript.

Blazor is based on a powerful and flexible component model for building rich interactive web UI. You can implement Blazor UI components using a combination of .NET code and Razor syntax: an elegant melding of HTML and C#. Blazor components can seamlessly handle UI events, bind to user input, and efficiently render UI updates.

This has multiple advantages,

Don’t get me wrong, JavaScript is not thrown away, if you want you can invoke JavaScript code from C# and C# code from JavaScript.

There are two ways these Blazor components can be hosted to create your web app.

1. Blazor Server

In a Blazor Server app, the components run on the server using .NET Core. All UI interactions and updates are handled using a real-time WebSocket connection with the browser. Blazor Server apps are fast to load and simple to implement. Support for Blazor Server is available with .NET Core 3.1 LTS.

With the Blazor Server hosting model, the app is executed on the server from within an ASP.NET Core app. UI updates, event handling, and JavaScript calls are handled over a SignalR connection. [Read more]

2. Blazor WebAssembly

The principal hosting model for Blazor is running client-side in the browser on WebAssembly. The Blazor app, its dependencies, and the .NET runtime are downloaded to the browser. The app is executed directly on the browser UI thread. UI updates and event handling occur within the same process. The app’s assets are deployed as static files to a web server or service capable of serving static content to clients. [Read more]

Blazor WebAssembly is now the second supported way to host your Blazor components: client-side in the browser using a WebAssembly-based .NET runtime. Blazor WebAssembly includes a proper .NET runtime implemented in WebAssembly, a standardized bytecode for the web (learn more about WebAssembly, in a nutshell WebAssembly enabled developers to use other programming languages to create web apps other than JavaScript). This .NET runtime is downloaded with your Blazor WebAssembly app and enables running normal .NET code directly in the browser. No plugins or code transpilation are required. Blazor WebAssembly works with all modern web browsers, both desktop and mobile. Similar to JavaScript, Blazor WebAssembly apps run securely on the user’s device from within the browser’s security sandbox. These apps can be deployed as completely standalone static sites without any .NET server component at all, or they can be paired with ASP.NET Core to enable full stack web development with .NET, where code can be effortlessly shared with the client and server.

In this article we will be using Blazor WebAssembly

Where can I use Blazor?

You can use Blazor on any browser that supports WebAssembly. All major browsers support WebAssembly and following diagram verifies it. (However it is understood that sometimes we need to support older browsers such as Internet Explorer, if this is your case you cannot use Blazor on the client side.)

Source — caniuse.com on 28/06/2020

OK, time to code.

Setting up development environment.

You can use either use .NET Core CLI or Visual Studio 2019, to get started with minimum requirements we will use .NET Core CLI, if you want to use Visual Studio visit official Microsoft documentation, set things up and skip this section. Even if you use Visual Studio, you can follow along because everything else will be similar in both environments.

dotnet --version
dotnet new blazorwasm -o WebApplicationcd WebApplicationcode .

After Visual Studio code is launched, open a terminal using Ctrl + Shift + ` and execute command,

dotnet watch run
Hello, world!

OK, moving forward. Before we start Blazor you need to have some understanding about Razor. With Razor we can write C# and HTML code combined in the same file. Razor syntax uses @ symbol to switch between C# code and HTML. This allows us to declare variables within HTML structure. Razor code is usually written in .cshtml files. But in this case we write our code in .razor files to work with Razor Components. Confused? Yes me too. Let’s demonstrate!

Open index.razor

@page "/"<h1>Hello, world!</h1>
Welcome to Blazor!
<SurveyPrompt Title="How is Blazor working for you?" />

Remove everything in this file keeping first two lines.

@page "/"<h1>Hello, world!</h1>

The @page "/" specifies which page is this, in above case it is the root or the index page, which is the page you see when you go to the https://localhost:5001. Next you see a <h1> tag. So now you know we can insert HTML in it. Now let’s insert some C# code.

@page "/"<h1>Hello, @myVariable</h1>@code{
string myVariable = "Blazor!";
}

We write C# code in this @code{ } section. We have created a string variable myVariable and assigned value “Blazor!”. Try reloading the page in the browser.

If you have experience in any other front end frameworks like Angular, this is exactly like using typescript to manipulate HTML. Okay let’s do something little bit advanced.

Loops

First thing you should notice in the foreach loop. Which creates a list of checkboxes and a label for the checkbox. And then you should look for List of todos. We have defined a Class Todo and then we have initialized a list of objects (3 objects) of that class, we have binded the Done property of that class with the checkbox, because then we can count the number of not done items using @todos.Count(todo => !todo.Done)

Hopefully you may have some understanding now about what is blazor and how everything adds up.

MarkupStrings

Strings are normally rendered using DOM text nodes, which means that any markup they may contain is ignored and treated as literal text. Let me demonstrate. Add <b></b> tag to ‘Corn’ as follows and observe the output.

This is not what we expect right? So to render raw HTML, wrap the HTML content in a MarkupString value. The value is parsed as HTML or SVG and inserted into the DOM.

Change the <label> tag as follows.

<label>@((MarkupString)todo.Item)</label>

See! this is how it’s done.

Razor Components.

Components are the centerpiece of Blazor. Literally almost everything is a component in Blazor. A component is a reusable piece of user interface, which may contain logic. These components are called Razor components, For example a component could be something as simple as a button or as large as a form. In the end are compiled to C# classes.

Take a look at the Pages folder and Shared folder. In the pages folder you can find the routable components. A routable component is a component that have a page that have a page directive, the @page directive allows you to assign a URL to a component. those components that are in the shared folder do not have the page directive. For example we can opened an NavMenu component and as you can see at the top of the component we don’t have a page directive.

We’ll implement our own component to move the code we just wrote. Create a new component ToDoList.razor as follows in shared folder.

Then in the Index.razor we can add that component as follows.

Now if you reload the application you can see that it is working and providing the same output as before. This way you can create reusable components which can be used in anywhere in your application.

HttpClient Service.

In a Blazor WebAssembly app, HttpClient is available as a preconfigured service for making requests back to the origin server.

In the Program.cs check if following line exits.

builder.Services.AddTransient(
sp => new HttpClient {
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

HttpClient and JSON helpers are also used to call third-party web API endpoints. HttpClient is implemented using the browser Fetch API and is subject to its limitations, including enforcement of the same origin policy.

The client’s base address is set to the originating server’s address. Inject an HttpClient instance using the @inject directive:

@using System.Net.Http
@inject HttpClient Http

Before you make the request, you need to keep in mind that Blazor enforces the same origin policy. If you are using a .net core API you need to add the following CORS middleware configuration to the web API’s service’s Startup.Configure method:

app.UseCors(policy => 
policy.WithOrigins("http://localhost:5000", "https://localhost:5001")
.AllowAnyMethod()
.WithHeaders(HeaderNames.ContentType));

To demonstrate this let’s create a new component in pages folder named CallWebApi.razor and add following code segment. For this implementation we assume that our todo items comes from an API endpoint: https://localhost:10000/api/TodoItems

GetFromJsonAsync: Sends an HTTP GET request and parses the JSON response body to create an object. What about other HTTP methods?

Vist here for more information. Don’t worry, these are very simple. Check out this file from this project for a more comprehensive implementation of the above methods.

Here we also utilizes Blazor life cycle method OnInitializedAsync.

OnInitializedAsync and OnInitialized are invoked when the component is initialized after having received its initial parameters from its parent component in SetParametersAsync. Use OnInitializedAsync when the component performs an asynchronous operation and should refresh when the operation is completed.

Blazor Application Lifecycle

The Blazor application lifecycle methods provide a way to execute additional functionality or operations on a Razor component while it is being initialized and being rendered. The following are the lifecycle methods that are executed during the initializing and rendering of the component.

Blazor Lifecycle Methods — Flow

Another important method in the life cycle is OnAfterRender and OnAfterRenderAsync

OnAfterRenderAsync and OnAfterRender methods are called after the component has finished rendering. At this point, all the elements and the component references are populated. The methods can be used to perform additional initialization of the component, such as event attaching an event listener or initializing the JavaScript libraries which require the DOM elements to be present in order to work.

Let’s add a new page with route /LifeCycle to see how these methods are invoked.

This concludes the Getting Started with Blazor WebAssembly post and hopefully you understand something more than when you started. The official documentation is always a good starting point. Let’s see what the Blazor framework would present us in the future.

Project I created in support for this blog post is on github.

Systems Design • Social Innovation • Cloud • ML