ASP.NET Core Blazor 簡介Introduction to ASP.NET Core Blazor

作者:Daniel RothLuke LathamBy Daniel Roth and Luke Latham

歡迎使用 Blazor!Welcome to Blazor!

Blazor 是使用 .NET 建立互動式用戶端 web UI 的架構: is a framework for building interactive client-side web UI with .NET:

  • 使用 C# 而不是 JavaScript 來建立豐富的互動式 UI。Create rich interactive UIs using C# instead of JavaScript.
  • 共用以 .NET 撰寫的伺服器端與用戶端應用程式邏輯。Share server-side and client-side app logic written in .NET.
  • 將 UI 轉譯為 HTML 和 CSS 以支援寬瀏覽器,包括行動裝置瀏覽器。Render the UI as HTML and CSS for wide browser support, including mobile browsers.

使用 .NET 進行用戶端網頁程式開發可提供下列優點:Using .NET for client-side web development offers the following advantages:

  • 以 C# 撰寫而不是 JavaScript。Write code in C# instead of JavaScript.
  • 利用 .NET 程式庫的現有 .NET 生態系統。Leverage the existing .NET ecosystem of .NET libraries.
  • 跨伺服器和用戶端共用應用程式邏輯。Share app logic across server and client.
  • 從 .NET 的效能、可靠性和安全性中獲益。Benefit from .NET's performance, reliability, and security.
  • 使用 Windows、Linux 和 macOS 版的 Visual Studio 保持生產力。Stay productive with Visual Studio on Windows, Linux, and macOS.
  • 以常用的語言、架構和工具建置,不僅穩定、功能豐富,而且容易使用。Build on a common set of languages, frameworks, and tools that are stable, feature-rich, and easy to use.

元件Components

Blazor 應用程式是以元件為基礎。 apps are based on components. Blazor 中的元件是 UI 的元素,例如頁面、對話方塊或資料輸入表單。A component in Blazor is an element of UI, such as a page, dialog, or data entry form.

元件是內建在 .NET 組件中且具有下列功能的 .NET 類別:Components are .NET classes built into .NET assemblies that:

  • 定義彈性 UI 轉譯邏輯。Define flexible UI rendering logic.
  • 處理使用者動作。Handle user events.
  • 可以為巢狀結構,且可重複使用。Can be nested and reused.
  • 能以 Razor 類別庫NuGet 套件方式共用及散發。Can be shared and distributed as Razor class libraries or NuGet packages.

該元件類別通常使用副檔名為 .razorRazor 標記頁面形式撰寫而成。The component class is usually written in the form of a Razor markup page with a .razor file extension. Blazor 中的元件正式稱為Razor 元件Components in Blazor are formally referred to as Razor components. Razor 是結合了 HTML 標記與 C# 程式碼的語法,專為開發人員的生產力而設計。Razor is a syntax for combining HTML markup with C# code designed for developer productivity. Razor 可讓您在同一個具有 IntelliSense 支援的檔案中,於 HTML 標記和 C# 之間切換。Razor allows you to switch between HTML markup and C# in the same file with IntelliSense support. Razor Pages 和 MVC 也會使用 Razor。Razor Pages and MVC also use Razor. 不同於 Razor Pages 和 MVC,它們是圍繞著要求/回應模型而建置的,元件則是專門用來處理用戶端 UI 邏輯與組合。Unlike Razor Pages and MVC, which are built around a request/response model, components are used specifically for client-side UI logic and composition.

下列 Razor 標記示範一個元件 (Dialog.razor),此元件可巢狀於另一個元件內:The following Razor markup demonstrates a component (Dialog.razor), which can be nested within another component:

<div>
    <h1>@Title</h1>

    @ChildContent

    <button @onclick="OnYes">Yes!</button>
</div>

@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    private void OnYes()
    {
        Console.WriteLine("Write to the console in C#! 'Yes' button was selected.");
    }
}

對話方塊的內文內容 (ChildContent) 和標題 (Title) 均由要在 UI 中使用此元件的元件所提供。The dialog's body content (ChildContent) and title (Title) are provided by the component that uses this component in its UI. OnYes 是按鈕的 onclick 事件所觸發的 C# 方法。OnYes is a C# method triggered by the button's onclick event.

Blazor 使用自然 HTML 標籤來進行 UI 組合。 uses natural HTML tags for UI composition. HTML 元素會指定元件,而標記的屬性 (Attribute) 會將值傳遞至元件的屬性 (Property)。HTML elements specify components, and a tag's attributes pass values to a component's properties.

在下列範例中, Index 元件使用 Dialog 元件。In the following example, the Index component uses the Dialog component. ChildContentTitle 是由 <Dialog> 元素的屬性與內容設定的。ChildContent and Title are set by the attributes and content of the <Dialog> element.

Index.razorIndex.razor:

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<Dialog Title="Blazor">
    Do you want to <i>learn more</i> about Blazor?
</Dialog>

當您於瀏覽器中存取父代 (Index.razor) 時,即會轉譯此對話方塊:The dialog is rendered when the parent (Index.razor) is accessed in a browser:

瀏覽器中轉譯的對話方塊元件

在應用程式中使用此元件時,Visual StudioVisual Studio Code (英文) 中的 IntelliSense 會藉由完成語法和參數來加快開發速度。When this component is used in the app, IntelliSense in Visual Studio and Visual Studio Code speeds development with syntax and parameter completion.

元件會轉譯為瀏覽器文件物件模型 (DOM) 的記憶體內部表示法 (稱為「轉譯樹」),可用來以彈性且有效率的方式更新 UI。Components render into an in-memory representation of the browser's Document Object Model (DOM) called a render tree, which is used to update the UI in a flexible and efficient way.

Blazor WebAssembly WebAssembly

重要

Blazor 預覽中的 WebAssemblyBlazor WebAssembly in preview

ASP.NET Core 3.0 支援 Blazor ServerBlazor Server is supported in ASP.NET Core 3.0. ASP.NET Core 3.1 Blazor WebAssembly處於預覽狀態。Blazor WebAssembly is in preview for ASP.NET Core 3.1.

Blazor WebAssembly 是使用 .NET 建立互動式用戶端 web 應用程式的單一頁面應用程式架構。 WebAssembly is a single-page app framework for building interactive client-side web apps with .NET. Blazor WebAssembly 會使用開放式 web 標準,而不需要外掛程式或程式碼轉譯,並可在所有新式網頁瀏覽器中運作,包括行動瀏覽器。 WebAssembly uses open web standards without plugins or code transpilation and works in all modern web browsers, including mobile browsers.

在網頁瀏覽器內執行 .NET 程式碼已可藉由 WebAssembly (縮寫為 wasm) 達成。Running .NET code inside web browsers is made possible by WebAssembly (abbreviated wasm). WebAssembly 是一種精簡的位元組程式碼格式,針對快速下載和最快執行速度而最佳化。WebAssembly is a compact bytecode format optimized for fast download and maximum execution speed. WebAssembly 是開放式的 Web 標準,在不含外掛程式的網頁瀏覽器中支援。WebAssembly is an open web standard and supported in web browsers without plugins.

WebAssembly 程式碼可以透過 JavaScript 存取瀏覽器的完整功能,稱為 「JavaScript 互通性」(或 JavaScript Interop)。WebAssembly code can access the full functionality of the browser via JavaScript, called JavaScript interoperability (or JavaScript interop). 在瀏覽器中透過 WebAssembly 執行的 .NET 程式碼會在瀏覽器的 JavaScript 沙箱執行,且受沙箱所提供對用戶端電腦之惡意動作的保護。.NET code executed via WebAssembly in the browser runs in the browser's JavaScript sandbox with the protections that the sandbox provides against malicious actions on the client machine.

[!OP.無 LOC (Blazor)] WebAssembly 會在瀏覽器中使用 WebAssembly 執行 .NET 程式碼。 WebAssembly runs .NET code in the browser with WebAssembly.

在瀏覽器中建立並執行 Blazor WebAssembly 應用程式時:When a Blazor WebAssembly app is built and run in a browser:

  • C# 程式碼檔案和 Razor 檔案會編譯成 .NET 組件。C# code files and Razor files are compiled into .NET assemblies.
  • 組件和 .NET 執行階段會下載至瀏覽器中。The assemblies and the .NET runtime are downloaded to the browser.
  • Blazor WebAssembly 會啟動 .NET 執行時間,並設定執行時間以載入應用程式的元件。 WebAssembly bootstraps the .NET runtime and configures the runtime to load the assemblies for the app. Blazor WebAssembly 執行時間會使用 JavaScript interop 來處理 DOM 操作和瀏覽器 API 呼叫。The Blazor WebAssembly runtime uses JavaScript interop to handle DOM manipulation and browser API calls.

發佈的應用程式大小 (它的「承載大小」) 是應用程式使用性的重要效能因素。The size of the published app, its payload size, is a critical performance factor for an app's useability. 大型應用程式需要相對較長的時間才能下載至瀏覽器,這點會對使用者體驗造成傷害。A large app takes a relatively long time to download to a browser, which diminishes the user experience. Blazor WebAssembly 會優化承載大小以縮短下載時間: WebAssembly optimizes payload size to reduce download times:

  • 若應用程式是透過中繼語言 (IL) 連接器所發佈的,則會移除未使用的程式碼。Unused code is stripped out of the app when it's published by the Intermediate Language (IL) Linker.
  • HTTP 回應會進行壓縮。HTTP responses are compressed.
  • .NET 執行階段與組件會在瀏覽器中進行快取。The .NET runtime and assemblies are cached in the browser.

Blazor 伺服器 Server

Blazor 將元件轉譯邏輯與 UI 更新的套用方式分離。 decouples component rendering logic from how UI updates are applied. Blazor Server 提供在 ASP.NET Core 應用程式中將 Razor 元件裝載在伺服器上的支援。 Server provides support for hosting Razor components on the server in an ASP.NET Core app. UI 更新會透過SignalR連接來處理。UI updates are handled over a SignalR connection.

執行階段會處理將 UI 事件從瀏覽器傳送到伺服器,然後在執行元件之後,套用由伺服器傳送回瀏覽器的 UI 更新。The runtime handles sending UI events from the browser to the server and applies UI updates sent by the server back to the browser after running the components.

Blazor 伺服器用來與瀏覽器通訊的連接也會用來處理 JavaScript interop 呼叫。The connection used by Blazor Server to communicate with the browser is also used to handle JavaScript interop calls.

[!OP.無 LOC (Blazor)] 伺服器會在伺服器上執行 .NET 程式碼,並透過 [!,與用戶端上的檔物件模型互動OP.無-LOC (SignalR)] 連接 Server runs .NET code on the server and interacts with the Document Object Model on the client over a SignalR connection

JavaScript InteropJavaScript interop

對於需要協力廠商 JavaScript 程式庫和瀏覽器 API 存取的應用程式,元件能夠和 JavaScript 交互操作。For apps that require third-party JavaScript libraries and access to browser APIs, components interoperate with JavaScript. 元件可以使用 JavaScript 可以使用的任何程式庫或 API。Components are capable of using any library or API that JavaScript is able to use. C# 程式碼可以呼叫進入 JavaScript 程式碼,而 JavaScript 程式碼可以呼叫進入 C# 程式碼。C# code can call into JavaScript code, and JavaScript code can call into C# code. 如需詳細資訊,請參閱ASP.NET Core Blazor JavaScript interopFor more information, see ASP.NET Core Blazor JavaScript interop.

程式碼共用和 .NET StandardCode sharing and .NET Standard

Blazor 會實行.NET Standard 2.0 implements .NET Standard 2.0. .NET Standard 是所有 .NET 實作都具備的 .NET API 正式規格。.NET Standard is a formal specification of .NET APIs that are common across .NET implementations. .NET Standard 類別庫可以在不同的 .NET 平臺之間共用,例如 Blazor、.NET Framework、.NET Core、Xamarin、Mono 和 Unity。.NET Standard class libraries can be shared across different .NET platforms, such as Blazor, .NET Framework, .NET Core, Xamarin, Mono, and Unity.

網頁瀏覽器內不適用的 API (例如,存取檔案系統、開啟通訊端與執行緒) 均會擲回 PlatformNotSupportedExceptionAPIs that aren't applicable inside of a web browser (for example, accessing the file system, opening a socket, and threading) throw a PlatformNotSupportedException.

其他資源Additional resources