Blazor

Blazor

  • Introduction to Blazor

  • A real-time framework that can run client logic on the server, and client UI events are sent back to the server using Signalr
  • Official introduction to Blazor: 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 over a SignalR connection. SignalR is also 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.
      • The delay of the network will affect the delay of Blazor
      • Scenario: The concurrency is not high, and the user access is not large.
      • Good for debugging, no need to download the entire runtime

Blazor Server in  The .NET code runs on the server and interacts with the Document Object Model on the client through a SignalR connection

    • Blazor WebAssembly for building interactive client-side web apps using .NET.
      • With WebAssembly (abbreviated as ), you can 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
      • For runtime, the entire runtime will be downloaded
      • Advantages:
        • After the application is loaded on the client device, the UI interaction is fast and 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 side, the application can work offline (except for requests to the server’s API)
      • Disadvantages:
        • The initial load takes time. 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 and beyond.
        • The delay of interface switching is relatively long, which makes it uncomfortable to use.

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

    • You can see the binary file to be loaded in the webpage->application->Cache

  • WebAssembly vs Server
    • WebAssembly (WASM) is a binary instruction format that enables code to execute at near-native speed in web browsers. It aims 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. Simply put, when the Dll is loaded for the first time, it is downloaded to the browser through the server, and then all run 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, and database services.

    • 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 servers are designed to serve and respond to client requests. In some cases, WebAssembly can be used on the server side to improve server performance, but this is not its main purpose.

  • Officially Created by Blazor: Blazor Tutorial – Building Your First App (microsoft.com)

Projects are created and loaded in Visual Studio. Please use Solution Explorer to view the project contents.

Solution Explorer contains created for project  List of folders and files

Several files have been created to give you a simple Blazor app that works.

    • Program.cs is the entry point for the application that starts the server and configures application services and middleware within it.
    • App.razor is the root component of the application.
    • The

    • Pages directory contains some sample pages for the application.
    • BlazorApp.csproj defines the app project and its dependencies, and can be viewed by double-clicking the BlazorApp project node in Solution Explorer.
    • The launchSettings.json file in the

    • Properties directory is defined for the local development environmente> cascade parameters.
    • The component indicates that the authority authentication failed
    • The component indicates that the authority is being authenticated
// ---------- 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 a cascading parameter
    • Define a cascading parameter of type Task<AuthenticationState> to obtain authentication state 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
    • component indicates that the authority authentication is successful. Often used to display during asynchronous authentication
    • The component indicates that the authority 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] attribute
    • [Authorize] attribute is available in Razor components: commonly used in interfaces
    • Only use [Authorize] for @page components arriving 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)); } }

.razor ———-

@code {
private bool collapseNavMenu = true;

private string? NavMenuCssClass => collapseNavMenu ? “collapse” : null;

private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
}

  • [Authorize] attribute
    • [Authorize] attribute is available in Razor components: commonly used in interfaces
    • Only use [Authorize] for @page components arriving 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/

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
首页
微信
电话
搜索