4

In mid-April 2019, Microsoft launched Blazor. At that time, I felt that Blazor was simply an epoch-making thing, and it even allowed C# to run in the browser. Thinking that there may be no C/S architecture in the future, you can uninstall all the apps, and a browser on your computer is enough. Recently, I finally have time to learn about Blazor systematically. Below, I will write down the information I have learned and share it with you. I hope it will be helpful to you.

Blazor can use the strongly typed language C# to replace the JavaScript implementation logic, and reuse the logic in the front and back ends, or use the package in 1 . Part of it is implemented based on WebAssembly, so it does not rely on any plug-ins, let us quickly understand how Blazor makes C# run in the browser.

Blazor involves technology

Blazor 2 is part of the apt.net core ecology, and most of the technologies involved are also related to .net.

View layer, using Razor 3 technology for front-end layout rendering. Razor is a markup syntax, asp.net core's default view syntax. The most notable feature is that strongly typed (C#, VB, etc.) code can be written in the same file with HTML, and of course it can be separated. In a razor file, the words after the @ symbol are all strongly typed languages, which can be part of a line, a whole line, or a paragraph. The general approach in asp.net core is to embed strongly typed languages such as VB and C# into the web page. When the web page is requested, the embedded code is executed on the server side to dynamically generate the page.

When running in Blazor WebAssembly development mode, relying on WebAssembly 4 technology, it can be made into a static page without relying on any back-end server.

When developing and running in Blazor Server mode, it relies on SignalR 5 technology, and requires back-end server-side cooperation.

Introduction to Blazor

Blazor is a framework that uses interactive client-side Web UI generated by .NET. There is a huge difference from Vue, React, and Angular that the front-end students are familiar with.

Its biggest feature is the use of C# code (in theory, any language in the .NET ecosystem) instead of JavaScript to implement logic.

There are two different development modes

Blazor WebAssembly, C# code runs in the browser.
Blazor Server, C# code is executed on the server side, using SignalR to synchronize to the browser for update.

Blazor WebAssembly

Let us first take a brief look at WebAssembly (Wasm) 4 .

WebAssembly is a binary instruction format based on a stack virtual machine.
WebAssembly is a kind of assembly language.
WebAssembly has high performance and can cooperate with JavaScript.
WebAssembly is a part of W3C and is supported by modern browsers.

So now let us think about a question, how to make C# code run in the browser?

First, briefly recall how the C# code works. As shown in the figure below, we must first compile the C# source code into a dll file, and then load and execute it by the .net runtime.

image.png

How to make C# run in the browser? It seems that only a .net runtime running in the browser is missing. So should I use JavaScript to write a .net runtime? Don't worry, the dotnet community has a better solution.

In the directory.Build.props 7 in the dotnet/runtime 6 source code, we can see that there is a wasm as the compilation target, which is based on the runtime.netsembly of WebAssembly. Now that we know that C# code can be run in the browser, there is a place for Blazor to survive. (Of course, the fact is that the mono community first implemented the WebAssembly version of the .net runtime. It was later merged into the dotnet core runtime)

Let's take a look at how to create a Blazor project. There are two ways, 1. Use the command line, 2. Use an IDE, such as Visual Studio.

Command line tools are only for students who don’t want to install giant tools like Visual Studio and want to try new things. Can be used with any editor, such as Visual Studio Code. The following are the specific steps:

First, you need to download dotnet core 8 . Here is the dotnet core removal tool dotnet-core-uninstall 9 .
Use the command donet new -l to see all supported templates.
dotnet new blazorwasm in the blank directory to create a template project for Blazor WebAssembly.
Execute the command dotnet run start the website, which can be accessed in the browser.
It is easier to create with Visual Studio, just select the corresponding template.

It's finally time to code!

Let's first look at two key files, the C# entry file Program.cs and the HTML entry file index.html.

// Program.cs 文件
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
 
 
namespace BlazorWebAssembly
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
            // 上一行我们可以理解为,在 ID 是 app 的元素中渲染展示 Blazor WebAssembly,所以让网页的某一部分使用 Blazor 技术渲染也是可行的。
 
            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
 
            await builder.Build().RunAsync();
        }
    }
}
<!-- index.html 文件 -->
<!DOCTYPE html>
<html>
 
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>BlazorWebAssembly</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />
    <link href="BlazorWebAssembly.styles.css" rel="stylesheet" />
</head>
 
<body>
    <div id="app">Loading...</div>
 
    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">X</a>
    </div>
    <script src="_framework/blazor.webassembly.js"></script>
    <!-- blazor.webassembly.js 文件的作用有两个。
    1、下载 .net runtime, 依赖的类库以及项目编译后的文件。
    2、从 blazor.boot.json 中找到 C# 程序入口,并初始化运行。 -->
</body>
 
</html>

In the compiled files, we can see some files with the suffix br, because Blazor uses brotli with a higher compression rate by default. 10 for compression. I think I should recommend it here. Brotli is better than gzip. It can save more space.

image.png
The simple architecture developed by Blazor WebAssembly, as shown in the figure above, the execution of .net code and the rendering and redrawing of DOM elements are all performed in the browser.

Disadvantages: a large number of dependent files (.net runtime and dependent libraries) need to be loaded when opening the website for the first time; browsers are required to support WebAssembly. In caniuse, you can view the support of each browser for WebAssembly 11 .

Interaction between C# and JavaScript

There are two different ways of interaction, 1. Calling JavaScript code 12 from C#, 2. Calling C# code 13 from JavaScript.

First, call the JavaScript code from C#

First write a JavaScript global function, ready to be used by C#.

function buildObjctString(name, age) {
    const obj = { name, age }
    return JSON.stringify(obj)
}

It can be called like this in C#

@inject IJSRuntime JS
 
private async Task CSharpCallJS()
{
    var methodName = "buildObjctString";
    var name = "zpfe group";
    var age = 18;
    var data = await JS.InvokeAsync<string>(methodName, name, age);
}

Then, call the code of C# from JavaScript

// 这里的 C# 代码也是拿全局函数来示例,在函数头上加了注解。
[JSInvokable]
public static Task<string> GetTime(string param)
{
    return Task.FromResult($"{param},后面的来自C# {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
}

The calling method in JavaScript is

// 如果 C# 函数有参数,不传递会报错
const result = await DotNet.invokeMethodAsync("BlazorWebAssembly", "GetTime", "这个是 js 传入的参数");
alert(result)

This is just the simplest example. For more details, please check the reference link 12 13 .

debugging

Debugging with Visual Studio will be very easy. It is the same as the normal C# debugging method. Just click the breakpoint for debugging at the top of the code that needs to be debugged and press F5 to debug. JavaScript code can also be debugged in the same way.

Blazor Server

I personally think that Blazor Server was created to make up for the shortcomings of Blazor WebAssembly. The Blazor Server development method will rely heavily on SignalR 5 . Here is a brief introduction to SignalR, which is also derived from the ASPNET Core community and is an implementation based on the RPC protocol. To put it simply, you can use JavaScript code in the browser to call functions developed on the server through SignalR, or you can use SignalR on the server to call JavaScript functions in the browser. This method can avoid the problem of loading a large number of dependent files when the website is opened for the first time, and can also make up for the browser's support for WebAssembly, and it can even run in IE. However, the UI update and event processing of the website developed in this way need to call the server for processing through SignalR, which requires frequent data exchange with the server, which requires high computing power on the server. In my understanding, this method is only suitable for websites with a small number of users.

The way to use the command to create is dotnet new blazorserver .

I won't talk about creating it with Visual Studio.

image.png
The simple architecture based on the Blazor Server development method is shown in the figure above. All UI updates processed by C# need to be performed on the server side, and the update results are sent to the browser for update through SignalR technology. Event handling functions written in C# and interoperability between C# and JavaScript also require the same logic.

Other

I find two more interesting features 1. Blazor Destkop (.net core 6 will support), using Blazor WebAssembly to develop desktop applications. 2. Browser extension (the idea of the open source community 14 ), using Blazor WebAssembly to develop browser plug-ins.

For more interesting projects, please pay attention to awesome blazor 15 .

The code involved in the article has been shared on GitHub 16 .


智联大前端
1.2k 声望5.1k 粉丝

您好, 我们是【智联大前端​】。


引用和评论

0 条评论