Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Understanding Server-Side Blazor

DZone's Guide to

Understanding Server-Side Blazor

With its latest update, the Blazor framework now offers developers the ability to create server-side applications. Read on to learn how.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

Introduction

We all know that the Blazor framework is a client-side web framework. But is it possible to run a Blazor application separate from the UI thread? The latest version of Blazor (0.5.0) gives us the flexibility to run Blazor in a separate process from the rendering process. We are going to explore server-side Blazor in this article.

What Is Server-Side Blazor?

Since Blazor is a client-side web framework, the component logic and DOM interaction both happens in the same process.

However, the design of the Blazor framework is smart and flexible enough to run the application separate from rendering process. For example, we can run Blazor in a web worker thread separately from UI thread.

In this scenario, the UI thread will push the events to the Blazor worker thread and Blazor will push UI updates to the UI thread as needed. Although Blazor does not support this functionality yet, the Blazor framework is designed to handle such scenarios and is expected to support it in future releases.

Starting with Blazor 0.5.0, we can run a Blazor application on the server. It means that we can run Blazor components server-side on .NET Core while other functionalities, such as UI updates, event handling, and Javascript interop calls, are handled by a SignalR connection over the network. The .NET part runs under CoreCLR instead of WebAssembly which provides us access to the complete .NET ecosystem, debugging, JIT compilation, etc. This adds extensibility to the Blazor framework as the server-side Blazor uses the same component model as a client-side Blazor app.

Let us create our first server-side Blazor app and explore it to get a better understanding of this new feature.

Prerequisites

  • Install the .NET Core 2.1 or above SDK from here.
  • Install Visual Studio 2017 v15.7 or above from here.
  • Install ASP.NET Core Blazor Language Services extension from here.

Visual Studio 2017 versions below v15.7 does not support Blazor framework.

Creating Server-Side Blazor Application

Open Visual Studio and select File >> New >> Project.

After selecting the project, a "New Project" dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select "ASP.NET Core Web Application" from the available project types. Set the name of the project as ServerSideBlazor and press OK.

After clicking OK, a new dialog will open asking you to select the project template. You'll see two drop-down menus at the top left of the template window. Select ".NET Core" and "ASP.NET Core 2.1" from these dropdowns. Then, select "Blazor (Server-side in ASP.NET Core)" template and press OK.

This will create our server-side Blazor solution. You can observe the folder structure in Solution Explorer, as shown in the below image:

The solution has two project files:

  1. ServerSideBlazor.App: this is our ASP.NET Core hosted project.
  2. ServerSideBlazor.Server: this contains our server-side Blazor app.

All of our component logic lies in the server-side Blazor app. However, this logic does not run on the client-side in the browser, instead it runs on the server-side in the ASP.NET Core host application. This application uses blazor.server.js for bootstrapping instead of blazor.webassembly.js used by normal Blazor app. This allows the app to establish a SignalR connection over the network to handle UI updates and event forwarding. The blazor.server.js is present at "\ServerSideBlazor.App\bin\Debug\netstandard2.0\dist\_framework" folder and the <script> tag to include it in the project is present in wwwroot/index.html file.

The blazor.server.js is the only component that separates a server-side Blazor app with a client-side Blazor app. If we provide a reference to blazor.webassembly.js instead of blazor.server.js inside the index.html file then this application will behave as a client-side Blazor app.

The Blazor app is hosted by an ASP.NET Core app, which also sets up the SignalR endpoint. Since the Blazor app is running on the server, the event handling logic can directly access the server resources and services.

For example, if we want to fetch any data, we no longer need to issue an HTTP request, instead, we can configure a service on the server and use it to retrieve the data.

In the sample application that we have created, the  WeatherForecastService class is defined inside of the "ServerSideBlazor.App/Services" folder.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace ServerSideBlazor.App.Services
{
    public class WeatherForecastService
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
        {
            var rng = new Random();
            return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = startDate.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray());
        }
    }
}

Furthermore, we need to configure the service inside the  ConfigureServices method in the "ServerSideBlazor.App/startup.cs" file.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<WeatherForecastService>();
}

We will then inject the service into the FetchData.cshtml view page, where the method GetForecastAsync is invoked to fetch the data.

@using ServerSideBlazor.App.Services
@page "/fetchdata"
@inject WeatherForecastService ForecastService

// HTML DOM here.

@functions {
    WeatherForecast[] forecasts;

    protected override async Task OnInitAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Go ahead and launch the application in Google Chrome. It will open a browser window and the app will look like a normal Blazor app. Open the Chrome Dev Tools. Navigate to the "Network" tab and you'll see that the application has not downloaded any .NET runtimes or the app assembly.

This is because the app is running on the sever-side of .NET Core. Since the dependencies are not downloaded when the application is booted up, the size of the app is smaller and also it gets loaded faster compared to a normal Blazor app.

Advantages of Server-Side Blazor

Server-side Blazor application provides us many benefits.

  1. Since the UI update is handled over a SignalR connection, we can avoid unnecessary page refreshes.
  2. The app download size is smaller and the initial app loads faster.
  3. The Blazor component can take full advantage of server capabilities such as using .NET Core compatible APIs.
  4. It will also support existing .NET tooling like debugging the application and JIT compilation.
  5. Since server-side Blazor runs under native .NET Core process, and not under Mono WebAssembly, it is also supported on browsers that have no WebAssembly support.

There are also a few drawbacks to server-side Blazor apps.

  1. Since UI interaction involves SignalR communication, it adds one extra step in making network calls which results in latency.
  2. The scalability of apps to handle multiple client connections is also a challenge.

Conclusion

We have learned about the latest server-side Blazor application, introduced in the Blazor 0.5.0 release, and looked at how it is different from normal client-side Blazor apps. We also discussed the pros and cons of using a server-side Blazor app over a client-side blazor app.

You can check my other articles on Blazor here.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
web dev ,blazor ,tutorial ,server-side

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}