Blazor
-
Introduction to Blazor
- A real-time frame that can run client logic on the server and client UI events sent back to the server using Signalr
- Blazor official introduction: ASP.NET Core Blazor | Microsoft Learn
- Blazor Server supports hosting Razor components on the server in ASP.NET Core applications. UI updates can be handled via SignalR connections. SignalR is based on websocket. If the network environment is not good, it will be disconnected, and it will be disconnected if it is not operated for a long time.
- Network delay will affect Blazor’s delay problem
- Scenario: Concurrency is not high and user access is not large.
- Suitable for debugging, no need to download the entire runtime
- Blazor Server supports hosting Razor components on the server in ASP.NET Core applications. UI updates can be handled via SignalR connections. SignalR is based on websocket. If the network environment is not good, it will be disconnected, and it will be disconnected if it is not operated for a long time.
-
- Blazor WebAssembly for building interactive client-side web applications using .NET.
- WebAssembly (abbreviated as ) allows you to run .NET code inside a web browser. WebAssembly is a compressed bytecode format optimized for fast downloads and maximum execution speed.
- Similar to pure front-end, with high security performance
- Suitable for running, the entire runtime will be downloaded
- Advantages:
- After loading the application to the client device, UI interactions are responsive because the entire content of the application has been downloaded to the client device or client
- Since the application is downloaded on the client, the application can work offline (except for making requests to the server’s API)
- Disadvantages:
- Initial loading takes time. The application binaries must be downloaded to the client. Download time depends on the size of the application binary. Once the download is complete, the app loads faster the second time onward.
- The delay between interface switching is relatively long, which makes it uncomfortable to use.
- Blazor WebAssembly for building interactive client-side web applications using .NET.
-
- You can see the binary file to be loaded in the web page->Application->Cache
- WebAssembly vs Server
-
WebAssembly (WASM) is a binary instruction format that allows code to be executed at near-native speed in a web browser. It is designed to make complex web applications run faster and more efficiently by allowing developers to write code in languages other than JavaScript, such as C++, Rust, and Go. To put it simply, when the Dll is loaded for the first time, it is downloaded to the browser through the server, and then all runs in the browser.
-
Server is a computer program that provides services and responds to client requests. The server usually runs on a remote computer, communicates with the client through the network, and can provide various services, such as Web services, file sharing, database services, etc.
-
Thus, WebAssembly and servers are different types of technologies that serve different purposes. WebAssembly is designed to improve the performance and efficiency of web applications, while the server is designed to provide services and respond to client requests. In some cases, WebAssembly can be used server-side to improve server performance, but this is not its primary purpose.
-
- Blazor official creation: Blazor tutorial – generating the first application (microsoft.com)
Projects are created and loaded in Visual Studio. Please use Solution Explorer to view the project contents.
Several files have been created to provide you with a simple Blazor app that you can run.
-
Program.cs
is the entry point for starting the server and configuring application services and middleware within it.App.razor
is the root component of the application.Pages
directory contains some sample pages for your application.BlazorApp.csproj
defines the application project and its dependencies, and can be viewed by double-clicking the BlazorApp project node in Solution Explorer.Properties
file in thelaunchSettings.json
directory is defined for the local development environment.Cascade parameters.- component indicates that permission authentication failed
- The component indicates that permission authentication is in progress
The
The
// ---------- Index.razor - ---------- You are not authorized (This is a custom message) You are getting authorized (This is a custom message) Not foundSorry, there's nothing at this address.
- Get permissions and expose authentication status as cascading parameters
- Define cascading parameters of type
Task<
AuthenticationState>
to obtain authentication status data - Use the AuthorizeRouteView and CascadingAuthenticationState components in the
App
component to set theTask<
AuthenticationState>
cascading parameters. - The AuthorizeView component exposes a
context
variable of type AuthenticationState (@context
in Razor syntax), which can be used to access information about the logged in user - The component indicates that permission authentication is successful. Commonly used to display during asynchronous authentication
- component indicates that permission authentication failed
li>
- Define cascading parameters of type
// ---------- Index.razor - ---------- @page "/"Hello,@context.User.Identity.Name
Hello,Guest!
@inject IJSRuntime js; @code{ [CascadingParameter] private Task authenticationState{ get; set; } private async Task DisplayGreetingAlert() { var authState = await authenticationState; var message = $"Hello {authState.User.Identity.Name}"; await js.InvokeVoidAsync("alter", message); } }
- Log out and revoke authorization
// ---------- MainLayout.razor - ---------- @inherits LayoutComponentBase BlazorServerAuthenticationAndAuthorization @using BlazorServerAuthenticationAndAuthorization.Authentication; @inject AuthenticationStateProvider authStateProvider; @inject NavigationManager navManager @code { private async Task Logout() { var customAuthStateProvider = (CustomAuthenticationStateProvider)authStateProvider; await customAuthStateProvider.UpdateAuthenticationState(null); navManager.NavigateTo("/", true); } }
- Role-based and policy-based authorization
- The AuthorizeView component supports role-based or policy-based authorization. For role-based authorization, use the Roles parameter. Commonly used on NavMenu
// --------- - NavMenu.razor ----------@code { private bool collapseNavMenu = true; private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } }
[Authorize]
Features[Authorize]
attribute is available in Razor components: commonly used in interfaces- Use
[Authorize]
only for@page
components that arrive through the Blazor router. Authorization is only performed as an aspect of routing, not as a subcomponent rendered in the page.
// ---------- FetchData.razor - ---------- @page "/fetchdata" @using BlazorServerAuthenticationAndAuthorization.Data @inject WeatherForecastService ForecastService @*Allow administrator authorization attribute: lock the entire interface*@ @attribute [Authorize(Roles = "Administrator")] @if (forecasts == null) {Loading...
} else {
Date | Temp. (C) | Temp. (F) | Summary |
---|---|---|---|
@forecast.Date.ToShortDateString() | @forecast.TemperatureC | @forecast.TemperatureF | @forecast.Summary |
azor ———-
@code {
private bool collapseNavMenu = true;
private string? NavMenuCssClass => collapseNavMenu ? “collapse” : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
}
[Authorize]
Features[Authorize]
attribute is available in Razor components: commonly used in interfaces- Use
[Authorize]
only for@page
components that arrive through the Blazor router. Authorization is only performed as an aspect of routing, not as a subcomponent rendered in the page.
// ---------- FetchData.razor - ---------- @page "/fetchdata" @using BlazorServerAuthenticationAndAuthorization.Data @inject WeatherForecastService ForecastService @*Allow administrator authorization attribute: lock the entire interface*@ @attribute [Authorize(Roles = "Administrator")] @if (forecasts == null) {Loading...
} else {
Date | Temp. (C) | Temp. (F) | Summary |
---|---|---|---|
@forecast.Date.ToShortDateString() | @forecast.TemperatureC | @forecast.TemperatureF | @forecast.Summary |