title
stringlengths
3
46
content
stringlengths
0
1.6k
19:120
Then, blazor.webassembly.js downloads all resources listed in this file and verifies their hashes. All resources downloaded by blazor.webassembly.js are created when the application is built or published. Loading blazor.webassembly.js periodically updates the --blazor-load-percentage and --blazor-load-percentage-text CSS variables with the loading percentage in numeric format and as text, respectively.
19:121
AuthenticationService.js is added only when the project enables authentication and takes care of the OpenID Connect protocol used by Blazor to exploit other identity providers, to get bearer tokens, which are the preferred authentication credentials for clients that interact with a server through web APIs.
19:122
Authentication is discussed in more detail in the Authentication and authorization subsection later on in this chapter, while bearer tokens are discussed in the REST service authorization and authentication section of Chapter 15, Applying Service-Oriented Architectures with .NET.
19:123
The Blazor application entry point is in the BlazorReview->Program.cs file. This file doesn’t contain a class but just the code that must be executed when the application is launched:
19:124
var builder = WebAssemblyHostBuilder.CreateDefault(args);
19:125
builder.RootComponents.Add<App>(`#app`);
19:126
builder.RootComponents.Add< HeadOutlet>(`head::after`);
19:127
// Services added to the application
19:128
// Dependency Injection engine declared with statements like:
19:129
// builder.Services.Add...
19:130
await builder.Build().RunAsync();
19:131
19:132
In fact, the new Blazor WebAssembly project template takes advantage of this new way to define the application entry point that was introduced starting from .NET 7.
19:133
WebAssemblyHostBuilder is a builder for creating a WebAssemblyHost, which is a WebAssembly-specific implementation of the generic host discussed in the Using generic hosts subsection of Chapter 11, Applying a Microservice Architecture to Your Enterprise Application (you are encouraged to review that subsection). The first builder configuration instruction declares the Blazor root component (App), which will contain the whole component tree, and specifies in which HTML tag of the index.html page to place it (#app). More specifically, RootComponents.Add adds a hosted service that takes care of handling the whole Blazor component tree. We can run several Blazor WebAssembly user interfaces on the same HTML page by calling RootComponents.Add several times, each time with a different HTML tag reference.
19:134
As the default, just another root component is added, HeadOutlet, and is placed immediately after the HTML Head tag. It is used to dynamically change the index.html title (the text shown in the browser tab). For more information on the HeadOutlet component, see the Modifying HTML <head> content from Blazor components subsection.
19:135
builder.Services contains all the usual methods and extension methods to add services to the Blazor application dependency engine: AddScoped, AddTransient, AddSingleton, and so on. Like in ASP.NET Core MVC applications (Chapter 17, Presenting ASP.NET Core, and Chapter 18, Implementing Frontend Microservices with ASP.NET Core), services are the preferred places to implement business logic and store shared state. While in ASP.NET Core MVC services were usually passed to controllers, in Blazor WebAssembly, they are injected into components.
19:136
The default project scaffolded by Visual Studio contains just two services, one for communicating with the server and the other for handling OAuth-based authentication. We will discuss both of them later on in this chapter.
19:137
The next subsection explains how the root App component simulates page changes.
19:138
Routing
19:139
The root App class referenced by the host-building code is defined in the BlazorReview ->App.razor file. App is a Blazor component, and like all Blazor components, it is defined in a file with a .razor extension and uses Razor syntax enriched with component notation, that is, with HTML-like tags that represent other Blazor components. It contains the whole logic for handling application pages:
19:140
<CascadingAuthenticationState>
19:141
<Router AppAssembly=`@typeof(App).Assembly`>
19:142
<Found Context=`routeData`>
19:143
<AuthorizeRouteView RouteData=`@routeData`
19:144
DefaultLayout=`@typeof(MainLayout)`>
19:145
<NotAuthorized>
19:146
@*Template that specifies what to show
19:147
when user is not authorized *@
19:148
</NotAuthorized>
19:149
</AuthorizeRouteView>
19:150
<FocusOnNavigate RouteData=`@routeData` Selector=`h1`>
19:151
</Found>
19:152
<NotFound Layout=`@typeof(MainLayout)`>
19:153
<PageTitle>Not found<PageTitle>
19:154
<LayoutView Layout=`@typeof(MainLayout)`>
19:155
<p>Sorry, there's nothing at this address.</p>
19:156
</LayoutView>
19:157
</NotFound>
19:158
</Router>
19:159
</CascadingAuthenticationState>
19:160
19:161
All tags in the preceding code represent either components or particular component parameters, called templates. Components will be discussed in detail throughout the chapter. For the moment, imagine them as a kind of custom HTML tags that we can somehow define with C# and Razor code. Templates, instead, are parameters that accept Razor markup as values. Templates are discussed in the Templates and cascading parameters subsection later on in this section.
19:162
The CascadingAuthenticationState component only has the function of passing authentication and authorization information to all components of the component tree that is inside of it. The Blazor project template generates it only if one chooses to add authorization during project creation.
19:163
The Router component is the actual application router. It scans the assembly passed in the AppAssembly parameter looking for components containing routing information, that is, for components that can work as pages. In the Blazor project template, the Router component is passed the assembly that contains the class of the App component, that is, the main application. Pages contained in other assemblies can be added through the AdditionalAssemblies parameter, which accepts an IEnumerable of assemblies.
19:164
After that, the router intercepts all page changes performed either by code or through the usual <a> HTML tags that point to an address inside of the application base address. Navigation can be handled by code by requiring a NavigationManager instance from dependency injection.
19:165
The Router component has two templates, one for the case where a page for the requested URI is found (Found), and the other for the case where it is not found (NotFound). When the application uses authorization, the Found template consists of the AuthorizeRouteView components, which further distinguish whether the user is authorized to access the selected page or not. When the application doesn’t use authorization, the Found template consists of the RouteView component:
19:166
<RouteView RouteData=`@routeData` DefaultLayout=`@typeof(MainLayout)` />
19:167
19:168
RouteView takes the selected page and renders it inside the layout page specified by the DefaultLayout parameter. This specification acts as a default since each page can override it by specifying a different layout page. In the Blazor project template, the default layout page is in the BlazorReview->Layout->MainLayout.razor file.
19:169
Blazor layout pages work similarly to ASP.NET Core MVC layout pages, described in the Reusing view code subsection of Chapter 17, Presenting ASP.NET Core, the only difference being that the place to add the page markup is specified with @Body:
19:170
<article class=`content px-4`>
19:171
@Body
19:172
</article>
19:173
19:174
If the application uses authorization, AuthorizeRouteView works like RouteView, but it also allows the specification of a template for a case where the user is not authorized:
19:175
<NotAuthorized>
19:176
@if (!context.User.Identity.IsAuthenticated)
19:177
{
19:178
<RedirectToLogin />
19:179
}
19:180
else
19:181
{
19:182
<p role =`alert`>You are not authorized to access this resource.</p>
19:183
}
19:184
</NotAuthorized>
19:185
19:186
If the user is not authenticated, the RedirectToLogin component uses a NavigationManager instance to move to the login logic page; otherwise, it informs the users that they haven’t got enough privileges to access the selected page.
19:187
Blazor WebAssembly also allows the lazy loading of assemblies to reduce the initial application loading time, but we will not discuss it here for lack of space. The Further reading section contains references to the official Blazor documentation.
19:188
As we will discuss in more detail later on in this chapter, the PageTitle component enables the developer to set the page title that appears in the browser tabs. The FocusOnNavigate component, instead, sets the HTML focus on the first HTML element that satisfies the CSS selector passed in its Selector parameter, immediately after a page is navigated.
19:189
Blazor pages and components
19:190
In this section, you will learn the fundamentals of Blazor components, including how to construct a component, the structure of components, how to attach events to HTML tags, how to specify the components’ characteristics, and how to use other components within your components. We have divided the content into several subsections:
19:191
19:192
Component structure
19:193
Templates and cascading parameters
19:194
Error handling
19:195
Events
19:196
Bindings
19:197
How Blazor updates HTML
19:198
Component lifecycle
19:199
19:200
Component structure
19:201
Components are the core of all main client frameworks. They are the key ingredient to building modular UI, whose parts are easily modifiable and reusable. In a few words, they are the graphical counterpart of classes. In fact, just like classes, they allow encapsulation and code organization. Moreover, the component architecture allows the formal definition of efficacious UI update algorithms, as we will see in the How Blazor updates HTML section of this chapter.
19:202
Components are defined in files with a .razor extension. Once compiled, they become classes that inherit from ComponentBase. Like all other Visual Studio project elements, Blazor components are available through the Add New Item menu. Usually, components to be used as pages are defined in the Pages folder, or in its subfolders, while other components are organized in different folders. Default Blazor projects add all their non-page components inside the Shared folder, but you can organize them differently.
19:203
By default, pages are assigned a namespace that corresponds to the path of the folder they are in. Thus, for instance, in our example project, all pages that are in the BlazorReview->Pages path are assigned to the BlazorReview.Pages namespace.
19:204
However, you can change this default namespace with an @namespace declaration placed in the declaration area that is at the top of the file. This area may also contain other important declarations. The following is an example that shows all declarations:
19:205
@page `/counter`
19:206
@layout MyCustomLayout
19:207
@namespace BlazorReview.Pages
19:208
@using Microsoft.AspNetCore.Authorization
19:209
@implements MyInterface
19:210
@inherits MyParentComponent
19:211
@typeparam T
19:212
@attribute [Authorize]
19:213
@inject NavigationManager navigation
19:214
19:215
The first two directives make sense only for components that must work as pages, while all others may appear in any component. Below is a detailed explanation of each declaration:
19:216
19:217
The @layout directive, when specified, overrides the default layout page with another component.
19:218
The @page directive defines the path of the page (route) within the application base URL. Thus, for instance, if our application runs at https://localhost:5001, then the URL of this page will be https://localhost:5001/counter. Page routes can also contain parameters, like in this example: /orderitem/{customer}/{order}. Parameter names must match public properties defined as parameters by the components. The match is case-insensitive. Parameters will be explained later on in this subsection.
19:219
The string that instantiates each parameter is converted into the parameter type, and if this conversion fails, an exception is thrown. This behavior can be prevented by associating a type with each parameter, in which case, if the conversion to the specified type fails, the match with the page URL fails. Only elementary types are supported: /orderitem/{customer:int}/{order:int}. As a default, parameters are obligatory; that is, if they are not found, the match fails and the router tries other pages. However, you can make parameters optional by post-fixing them with a question mark: /orderitem/{customer?:int}/{order?:int}. If an optional parameter is not specified, the default for its type is used.