title
stringlengths
3
46
content
stringlengths
0
1.6k
19:820
@code{
19:821
[Parameter] public string Action { get; set; }
19:822
}
19:823
19:824
The RemoteAuthenticatorView acts as an interface with the usual ASP.NET Core user login/registration system, and whenever it receives an “action” to perform, it redirects the user from the Blazor application to the proper ASP.NET Core server page (login, registration, logout, and user profile).
19:825
Once the user logs in, they are redirected to the Blazor application page that caused the login request. The redirect URL is computed by the BlazorReview.Layout->RedirectToLogin.razor component, which extracts it from the NavigationManager and passes it to the RemoteAuthenticatorView component. This time, the AuthenticationStateProvider is able to get the user information from the authentication cookie that has been created by the login operation.
19:826
It is possible both to design a custom OAuth provider for your Blazor application or to design a completely custom way to get a bearer token with an internal login Blazor page without leaving the Blazor application. In this last case, you must provide a custom implementation of the AuthenticationStateProvider. More details on these advanced custom scenarios are available in the official documentation reference in the Further reading section.
19:827
Having learned how to authenticate with an external OAuth provider and how to handle authorization within the Blazor application, we are ready to learn how to exchange data and how to authenticate with a REST API.
19:828
The next subsection describes a Blazor WebAssembly-specific implementation of the HttpClient class and related types.
19:829
Communication with the server
19:830
Blazor WebAssembly supports the same .NET HttpClient and HttpClientFactory classes described in the .NET HTTP clients section of Chapter 15, Applying Service-Oriented Architectures with .NET. However, due to the communication limitations of browsers, their implementations are different and rely on the browser’s fetch API.
19:831
In fact, for security reasons, all browsers, do not allow direct opening of generic TCP/IP connections but force all server communications to pass either through Ajax or through the fetch API.
19:832
This way, when you attempt a communication toward a URL that differs from the domain where the browser downloaded the SPA, the browser automatically switches to the CORS protocol, thus informing the server that the communication was started by a browser application that was downloaded by a different domain and that might potentially be a phishing website.
19:833
In turn, the server accepts CORS communications just from well-known domains that are pre-listed in its code. This way, the server is sure that the request can’t come from a phishing website.
19:834
In Chapter 15, Applying Service-Oriented Architectures with .NET, we analyzed how to take advantage of HttpClientFactory to define typed clients. You can also define typed clients in Blazor with exactly the same syntax.
19:835
However, since an authenticated Blazor application needs to send the bearer token created during the authentication process in each request to the application server, it is common to define a named client as shown here:
19:836
builder.Services.AddHttpClient(`BlazorReview.ServerAPI`, client =>
19:837
client.BaseAddress = new Uri(`https://<web api URL>`))
19:838
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
19:839
19:840
AddHttpMessageHandler adds a DelegatingHandler, that is, a subclass of the DelegatingHandler abstract class. Implementations of DelegatingHandler override its SendAsync method in order to process each request and each relative response:
19:841
protected override async Task<HttpResponseMessage> SendAsync(
19:842
HttpRequestMessage request,
19:843
CancellationToken cancellationToken)
19:844
{
19:845
//modify request
19:846
...
19:847
HttpResponseMessage= response = await base.SendAsync(
19:848
request, cancellationToken);
19:849
//modify response
19:850
...
19:851
return response;
19:852
}
19:853
19:854
If this bearer token is expired or is not found at all, it tries to get a new bearer token by using the authentication cookie received when the user manually logged in with the OAuth provider. This way, it can obtain a fresh bearer token without requesting a new manual login. If this attempt also fails, an AccessTokenNotAvailableException is thrown. Typically, this exception is captured and used to trigger a redirection to the login page by calling its Redirect method, as shown below:
19:855
try
19:856
{
19:857
//server call here
19:858
}
19:859
catch (AccessTokenNotAvailableException exception)
19:860
{
19:861
exception.Redirect();
19:862
}
19:863
19:864
If both the Blazor application and the Web API are deployed in different subfolders of the same domain, Blazor requests are issued without the CORS protocol, so they are automatically accepted by the server. Otherwise, the ASP.NET Core server must enable CORS requests, and must list the Blazor application URL among the allowed CORS domains with something like:
19:865
builder.Services.AddCors(o => {
19:866
o.AddDefaultPolicy(pbuilder =>
19:867
{
19:868
pbuilder.AllowAnyMethod();
19:869
pbuilder.WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization);
19:870
pbuilder.WithOrigins(https://<Blazor client url>, …, https://<Another client url>);
19:871
});
19:872
});
19:873
19:874
Then, you must also place the app.UseCors() middleware in the ASP.NET Core pipeline.
19:875
The example data shown on the Weather page of the ReviewBlazor application are downloaded from a static file located in the wwwroot/sample-data folder of the same Blazor application, so a normal, not-CORS request is issued and no bearer token is needed to request. Accordingly, the Weatherpage uses a default HttpClient defined in Program.cs as:
19:876
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
19:877
19:878
The next subsection explains how to improve the performance of computation-intensive applications with Blazor AOT compilation.
19:879
AOT compilation
19:880
Once uploaded in the browser, .NET assemblies are not compiled Just in Time (JIT) at their first execution as is the case for other platforms. Instead, they are interpreted by a very fast interpreter. Just the .NET runtime is pre-compiled and uploaded in the browser directly in WebAssembly.
19:881
JIT compilation is avoided since it would considerably increase the application start time, which is already quite high because of the high application download size (about 10 MB). In turn, the download size is high due to the .NET libraries that any Blazor application needs to work properly.
19:882
In order to reduce download size, during the compilation in release mode, Blazor .NET assemblies are tree-shaken to remove all unused types and methods. However, notwithstanding this tree-shaking, the typical download size remains quite high. A good download improvement is achieved with the default caching of the .NET runtime, which reduces the download size to 2-4 MB. However, the download size still remains high the first time a Blazor application is visited.
19:883
Starting from .NET 6, Blazor offers an alternative to JIT compilation: Ahead-of-Time (AOT) compilation. With AOT, all application assemblies are compiled into a unique WebAssembly file during the application publication.
19:884
AOT compilation is very slow and may last something like 10-30 minutes, even in the case of small applications. On the other hand, it must be executed only once when the application is published, so the compilation time doesn’t impact the application start time.
19:885
Unfortunately, AOT compilation more than doubles the download size, since the compiled code is more verbose than the source .NET code. Therefore, AOT should be adopted only in performance-critical applications that can trade a higher start time for better performance.
19:886
.NET WebAssembly AOT compilation requires an additional build tool that must be installed as an optional .NET SDK workload in order to use it. The first time, you can install it with the following shell command:
19:887
dotnet workload install wasm-tools
19:888
19:889
Instead, when a new .NET version is installed, we just need to launch the following command to update all previously installed workloads:
19:890
dotnet workload update
19:891
19:892
Once the AOT workload has been installed, AOT compilation can be enabled on a per-project basis by adding the <RunAOTCompilation>true</RunAOTCompilation> declaration to the Blazor project file, as shown here:
19:893
<Project Sdk=`Microsoft.NET.Sdk.BlazorWebAssembly`>
19:894
<PropertyGroup>
19:895
<TargetFramework>net8.0</TargetFramework>
19:896
<RunAOTCompilation>true</RunAOTCompilation>
19:897
</PropertyGroup>
19:898
...
19:899
19:900
The next section briefly discusses some of the most relevant third-party tools and libraries that complete Blazor’s official features and help increase productivity in Blazor projects.
19:901
Third-party tools for Blazor WebAssembly
19:902
Notwithstanding Blazor being a young product, its third-party tool and product ecosystem is already quite rich. Among the open source, free products, it is worth mentioning the Blazorise project (https://github.com/stsrki/Blazorise), which contains various free basic Blazor components (inputs, tabs, modals, and so on) that can be styled with various CSS frameworks, such as Bootstrap and Material. It also contains a simple editable grid and a simple tree view.
19:903
Also worth mentioning is BlazorStrap (https://github.com/chanan/BlazorStrap), which contains pure Blazor implementations of all Bootstrap 4 components and widgets.
19:904
Among all the commercial products, it is worth mentioning Blazor Controls Toolkit (https://blazorct.azurewebsites.net/), which is a complete toolset for implementing commercial applications. It contains all input types with their fallbacks in case they are not supported by the browser; all Bootstrap components; other basic components; a complete, advanced drag-and-drop framework; and advanced customizable and editable components, like detail views, detail lists, grids, and a tree-repeater (a generalization of the tree view). All components are based on a sophisticated metadata representation system that enables the user to design the markup in a declarative way using data annotations and inline Razor declarations.
19:905
Moreover, it contains additional sophisticated validation attributes, tools for undoing user input, tools for computing changes to send to the server, sophisticated client-side and server-side query tools based on the OData protocol, and tools to maintain and save the whole application state.
19:906
It is also worth mentioning the bUnit open-source project (https://github.com/egil/bUnit), which provides all the tools for testing Blazor components.
19:907
The Awesome Blazor project (https://github.com/AdrienTorris/awesome-blazor) lists thousands of open-source and commercial Blazor resources, such as tutorials, posts, libraries, and example projects.
19:908
A complete example of a Blazor WebAssembly application based on the WWTravelClub book use case can be found in the Using client technologies section of Chapter 21, Case Study. The next section explains how to use Blazor to implement cross-platform applications. The actual code is contained in the folder associated with this chapter in the GitHub repository of the book.
19:909
.NET MAUI Blazor
19:910
.NET MAUI is Microsoft’s advised choice to implement cross-platform applications. In fact, .NET MAUI applications can be just-in-time compiled for all Windows, Android, iOS, and other Linux-based devices. .NET MAUI contains a common abstraction of all target devices, and at the same time takes advantage of each device’s peculiarities by offering platform-specific libraries each containing platform-specific features of a target platform.
19:911
We will not describe .NET MAUI in detail, but after a short introduction to .NET MAUI, we will focus just on .NET MAUI Blazor. This way, by learning just Blazor, you will be able to develop single-page applications, progressive applications, and cross-platform applications.
19:912
What is .NET MAUI?
19:913
.NET MAUI extends Xamarin.Forms’ cross-platform capabilities from Android and iOS to also include Windows and macOS. Thus, .NET MAUI is a cross-platform framework for creating both native mobile and desktop apps with C#.
19:914
The basis of .NET MAUI is Xamarin.Forms. In fact, Microsoft has provided a guide for migrating original Xamarin.Forms apps to .NET MAUI, as can be seen at the following link: https://docs.microsoft.com/en-us/dotnet/maui/get-started/migrate. However, .NET MAUI has been conceived to be the new-generation framework for any native/desktop app development in C#:
19:915
19:916
Figure 19.2: .NET MAUI high-level architecture
19:917
There is a specific difference between Xamarin.Forms and .NET MAUI. In Xamarin.Forms, there is a specific native project for any kind of device we would like to publish to on the app, while in .NET MAUI, this approach is based on as single project targeting multiple platforms.
19:918
The next section explains how to use .NET MAUI to run a Blazor application as a native application.
19:919
Developing native applications with Blazor