At present, these hosting models are available for Blazor applications:

  • Blazor Server – A server-side ASP.NET Core application
  • Blazor WebAssembly – A client-side application that runs solely in the browser

In this article, we are going to run through the difference between the hosting models and look at integration examples. That’s go!

Blazor Server

Hosting a Blazor Server application relies on the standard ASP.NET Core sequence. You have your console application. This includes a Program class that builds and runs the application. In addition, you have your Startup class where configurations are tweaked.

Pages are built using Razor, and the technology varies between client and server-side methods within the application. For instance, for a client-side task, it takes advantage of WebAssembly from the browser. In contrast, for a server-side task, it uses a SignalR connection between the client and the server.

Blazor WebAssembly

You can host a Blazor WebAssembly separately without the need for an ASP.NET Core application. This works in a similar way to a JavaScript framework like React. In addition to your client-side application, if you need to include server-side functionality, you can host that in a separate API application and integrate the two together.

A major difference between Blazor WebAssembly and a JavaScript framework is that client-side methods use WebAssembly. WebAssembly is a client-side technology now integrated on all major browsers.

Create a Blazor Application in Visual Studio

Now that we know the difference between the different hosting models, that’s create one in Visual Studio.

Before we start, you need to make sure that you have Visual Studio 2019, version 16.4+. In addition, you need to make sure you have .NET Core SDK 3.1+ installed.

Open up Visual Studio 2019 and create a new project. Do a search for “Blazor App” and select that.

Create a new Blazor App in Visual Studio 2019

Set up the name of your application and you should be able to choose what kind of Blazor application you want to create. Either a Blazor Server App or a Blazor WebAssembly App.

Blazor Server or Blazor WebAssembly app

The Blazor WebAssembly App Option is Missing

This is because Blazor WebAssembly is in preview at present, and so it doesn’t come as standard in Visual Studio 2019. However, it’s relatively easy to install. All you need to do is to open up a Command Prompt window (in administration mode) and run the following:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.2.0-preview1.20073.1

Once that has been ran, the Blazor WebAssembly App option should be available.

An example of a Blazor Server Application

Now, I could run through how to integrate a Blazor Server application, but there’s no point. I’ve already done it! Look at my article entitled “Intro to Blazor and Creating a Blazor App from Scratch” and that will give you all the information you need.

An example of a Blazor WebAssembly Application

What I want to do is to concentrate on is looking at a Blazor WebAssembly application in more detail. The major difference with a Blazor WebAssembly application is the console application that builds it. Here is an example of how you build and run a Blazor WebAssembly application.

// Program.cs
public class Program
{
	public static async Task Main(string[] args)
	{
		var builder = WebAssemblyHostBuilder.CreateDefault(args);
		builder.RootComponents.Add<App>("app");
		
		await builder.Build().RunAsync();
	}
}

We now have a “WebAssemblyHostBuilder” class that works in a similar way as an API application would with the “WebHost” class. However, one of the big differences is that you need to add any route components to the builder. In this instance, we have added our “App” to the root components.

The “WebAssemblyHostBuilder” class includes an “IServiceCollection” property, allowing you to add services through dependency injection.

Calling the API

Requesting or sending data to the API is relatively straight forward in your Blazor WebAssembly application. You can take advantage of the “HttpClient” class that sits in “System.Net.Http”.

In this example, we inject the “HttpClient” class into our razor component. When it’s initialised, it makes a request to our API to get a list of all the languages that have currently been added. The user then has the ability to add a new language and click on a button. It’s when they click on the button that the razor component makes a POST request to the API with the new language. The API performs the request and returns an updated list of languages.

// Index.razor
@page "/"
@inject HttpClient httpClient
@using Newtonsoft.Json
    <h1>Here is a list of Languages</h1>
@if (Languages != null &amp;&amp; Languages.Any())
{
    <ul>
        @foreach (var language in Languages)
        {
            <li>@language</li>
        }
    </ul>
}
<input @bind="MessageInput" @bind:event="oninput" />
<button @onclick="MessageInputClick">Add Language</button>

@code {
    public string MessageInput { get; set; }

    public List<string> Languages { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Languages = await httpClient.GetJsonAsync<List<string>>("https://localhost:9000/api/language/getall");
    }

    public async Task MessageInputClick()
    {
        var postRequest = new Dictionary<string, string>();
        postRequest.Add("language", MessageInput);

        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("POST"),
            RequestUri = new Uri("https://localhost:9000/api/language/add"),
            Content = new StringContent(JsonConvert.SerializeObject(postRequest))
        };
        requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

        var response = await httpClient.SendAsync(requestMessage);
        var responseText = await response.Content.ReadAsStringAsync();

        Languages = JsonConvert.DeserializeObject<List<string>>(responseText);

        MessageInput = string.Empty;
    }
}

There’s No SSR

The following example shows a Blazor WebAssembly application running once initialised. We have taken a screenshot of how the page looks and how the source code is rendered.

The source code is what a bot would see if they crawl the page and did not execute any client-side technologies, such as WebAssembly and JavaScript. As you can see, the text “Here is a list of Languages” does not appear anywhere in the source code. This means that server-side rendering (SSR) is not enabled.

Blazor WebAssembly initialised application with source code

Demonstrations

You can watch the following video to see demonstrations of a Blazor Server application and a Blazor WebAssembly application:

The demonstrations referenced in the video can be downloaded from this GitHub Repository.

Which to Use?

I would personally use Blazor Server because of the SSR support. This is particularly important if you are expecting search engine bots to crawl your website. There is no reason why you can’t call an API to return the results within your Blazor Server application. However, the integration of server-side tools and SSR support will likely to cost you in performance, so it’s really down to you and your circumstances.

About David Grace

David Grace

I am a .NET developer, building web applications in .NET Framework and .NET Core with a SQL Server database.

Some of the .NET packages I have used include Entity Framework and MVC.

I've also used many JavaScript frameworks such as React and jQuery, and have experience building CSS in SASS.

Twitter Feed