Blazor

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 in  Run .NET code on the server and interact with the Document Object Model on the client through a SignalR connection

    • 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 onwards.
        • The delay between interface switching is relatively long, which makes it uncomfortable to use.

Blazor WebAssembly use  WebAssembly runs .NET code in the browser.

    • 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.

Solution Explorer contains the  List of folders and files

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 the application services and middleware within it.
    • App.razor is the root component of the application.
    • The

    • 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.
    • The

    • Properties file in the launchSettings.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
// ---------- Index.razor -  ----------

 
     
         
             
                 
                     You are not authorized (This is a custom message)
                 
                 
                     You are getting authorized (This is a custom message)
                 
             
             
         
         
             Not found
             
                 

Sorry, 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 the Task<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
    • li>

    • The component indicates that permission authentication is successful. Commonly used to display during asynchronous authentication
    • component indicates that permission authentication failed
// ---------- 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 { @foreach (var forecast in forecasts) { }
Date Temp. (C) Temp. (F) Summary
@forecast.Date.ToShortDateString() @forecast.TemperatureC @forecast.TemperatureF @forecast.Summary
} @code { private WeatherForecast[]? forecasts; protected override async Task OnInitializedAsync() { forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now)); } }

 

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 { @foreach (var forecast in forecasts) { }
Date Temp. (C) Temp. (F) Summary
@forecast.Date.ToShortDateString() @forecast.TemperatureC @forecast.TemperatureF @forecast.Summary
} @code { private WeatherForecast[]? forecasts; protected override async Task OnInitializedAsync() { forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now)); } }

 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/blazor-3/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索