Blazor WebAssembly 3.2.0 Preview 1 release now available

Daniel Roth

Today we released a new preview update for Blazor WebAssembly with a bunch of great new features and improvements.

Here’s what’s new in this release:

  • Version updated to 3.2
  • Simplified startup
  • Download size improvements
  • Support for .NET SignalR client

Get started

To get started with Blazor WebAssembly 3.2.0 Preview 1 install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.2.0-preview1.20073.1

That’s it! You can find additional docs and samples on https://blazor.net.

Upgrade an existing project

To upgrade an existing Blazor WebAssembly app from 3.1.0 Preview 4 to 3.2.0 Preview 1:

  • Update all Microsoft.AspNetCore.Blazor.* package references to 3.2.0-preview1.20073.1.
  • In Program.cs in the Blazor WebAssembly client project replace BlazorWebAssemblyHost.CreateDefaultBuilder() with WebAssemblyHostBuilder.CreateDefault().
  • Replace IWebAssemblyHost with WebAssemblyHost.
  • Replace IWebAssemblyHostBuilder with WebAssemblyHostBuilder.
  • Move the root component registrations in the Blazor WebAssembly client project from Startup.Configure to Program.cs by calling builder.RootComponents.Add<TComponent>(string selector).
  • Move the configured services in the Blazor WebAssembly client project from Startup.ConfigureServices to Program.cs by adding services to the builder.Services collection.
  • Remove Startup.cs from the Blazor WebAssembly client project.
  • If you’re hosting Blazor WebAssembly with ASP.NET Core, in your Server project replace the call to app.UseClientSideBlazorFiles<Client.Startup>(...) with app.UseClientSideBlazorFiles<Client.Program>(...).

Version updated to 3.2

In this release we updated the versions of the Blazor WebAssembly packages to 3.2 to distinguish them from the recent .NET Core 3.1 Long Term Support (LTS) release. There is no corresponding .NET Core 3.2 release – the new 3.2 version applies only to Blazor WebAssembly. Blazor WebAssembly is currently based on .NET Core 3.1, but it doesn’t inherit the .NET Core 3.1 LTS status. Instead, the initial release of Blazor WebAssembly scheduled for May of this year will be a Current release, which “are supported for three months after a subsequent Current or LTS release” as described in the .NET Core support policy. The next planned release for Blazor WebAssembly after the 3.2 release in May will be with .NET 5. This means that once .NET 5 ships you’ll need to update your Blazor WebAssembly apps to .NET 5 to stay in support.

Simplified startup

We’ve simplified the startup and hosting APIs for Blazor WebAssembly in this release. Originally the startup and hosting APIs for Blazor WebAssembly were designed to mirror the patterns used by ASP.NET Core, but not all of the concepts were relevant. The updated APIs also enable some new scenarios.

Here’s what the new startup code in Program.cs looks like:

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");

        await builder.Build().RunAsync();
    }
}

Blazor WebAssembly apps now support async Main methods for the app entry point.

To a create a default host builder, call WebAssemblyHostBuilder.CreateDefault(). Root components and services are configured using the builder; a separate Startup class is no longer needed.

The following example adds a WeatherService so it’s available through dependency injection (DI):

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddSingleton<WeatherService>();
        builder.RootComponents.Add<App>("app");

        await builder.Build().RunAsync();
    }
}

Once the host is built, you can access services from the root DI scope before any components have been rendered. This can be useful if you need to run some initialization logic before anything is rendered:

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddSingleton<WeatherService>();
        builder.RootComponents.Add<App>("app");

        var host = builder.Build();

        var weatherService = host.Services.GetRequiredService<WeatherService>();
        await weatherService.InitializeWeatherAsync();

        await host.RunAsync();
    }
}

The host also now provides a central configuration instance for the app. The configuration isn’t populated with any data by default, but you can populate it as required in your app.

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.Services.AddSingleton<WeatherService>();
        builder.RootComponents.Add<App>("app");

        var host = builder.Build();

        var weatherService = host.Services.GetRequiredService<WeatherService>();
        await weatherService.InitializeWeatherAsync(host.Configuration["WeatherServiceUrl"]);

        await host.RunAsync();
    }
}

Download size improvements

Blazor WebAssembly apps run the .NET IL linker on every build to trim unused code from the app. In previous releases only the core framework libraries were trimmed. Starting with this release the Blazor framework assemblies are trimmed as well resulting in a modest size reduction of about 100 KB transferred. As before, if you ever need to turn off linking, add the <BlazorLinkOnBuild>false</BlazorLinkOnBuild> property to your project file.

Support for the .NET SignalR client

You can now use SignalR from your Blazor WebAssembly apps using the .NET SignalR client.

To give SignalR a try from your Blazor WebAssembly app:

  1. Create an ASP.NET Core hosted Blazor WebAssembly app.

    dotnet new blazorwasm -ho -o BlazorSignalRApp
    
  2. Add the ASP.NET Core SignalR Client package to the Client project.

    cd BlazorSignalRApp
    dotnet add Client package Microsoft.AspNetCore.SignalR.Client
    
  3. In the Server project, add the following Hub/ChatHub.cs class.

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.SignalR;
    
    namespace BlazorSignalRApp.Server.Hubs
    {
        public class ChatHub : Hub
        {
            public async Task SendMessage(string user, string message)
            {
                await Clients.All.SendAsync("ReceiveMessage", user, message);
            }
        }
    }
    
  4. In the Server project, add the SignalR services in the Startup.ConfigureServices method.

    services.AddSignalR();
    
  5. Also add an endpoint for the ChatHub in Startup.Configure.

    .UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapHub<ChatHub>("/chatHub");
        endpoints.MapFallbackToClientSideBlazor<Client.Program>("index.html");
    });
    
  6. Update Pages/Index.razor in the Client project with the following markup.

    @using Microsoft.AspNetCore.SignalR.Client
    @page "/"
    @inject NavigationManager NavigationManager
    
    <div>
        <label for="userInput">User:</label>
        <input id="userInput" @bind="userInput" />
    </div>
    <div class="form-group">
        <label for="messageInput">Message:</label>
        <input id="messageInput" @bind="messageInput" />
    </div>
    <button @onclick="Send" disabled="@(!IsConnected)">Send Message</button>
    
    <hr />
    
    <ul id="messagesList">
        @foreach (var message in messages)
        {
            <li>@message</li>
        }
    </ul>
    
    @code {
        HubConnection hubConnection;
        List<string> messages = new List<string>();
        string userInput;
        string messageInput;
    
        protected override async Task OnInitializedAsync()
        {
            hubConnection = new HubConnectionBuilder()
                .WithUrl(NavigationManager.ToAbsoluteUri("/chatHub"))
                .Build();
    
            hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
            {
                var encodedMsg = user + " says " + message;
                messages.Add(encodedMsg);
                StateHasChanged();
            });
    
            await hubConnection.StartAsync();
        }
    
        Task Send() => hubConnection.SendAsync("SendMessage", userInput, messageInput);
    
        public bool IsConnected => hubConnection.State == HubConnectionState.Connected;
    }
    
  7. Build and run the Server project

    cd Server
    dotnet run
    
  8. Open the app in two separate browser tabs to chat in real time over SignalR.

Known issues

Below is the list of known issues with this release that will get addressed in a future update.

  • Running a new ASP.NET Core hosted Blazor WebAssembly app from the command-line results in the warning: CSC : warning CS8034: Unable to load Analyzer assembly C:\Users\user\.nuget\packages\microsoft.aspnetcore.components.analyzers\3.1.0\analyzers\dotnet\cs\Microsoft.AspNetCore.Components.Analyzers.dll : Assembly with same name is already loaded.

    • Workaround: This warning can be ignored or suppressed using the <DisableImplicitComponentsAnalyzers>true</DisableImplicitComponentsAnalyzers> MSBuild property.

Feedback

We hope you enjoy the new features in this preview release of Blazor WebAssembly! Please let us know what you think by filing issues on GitHub.

Thanks for trying out Blazor!

108 comments

Discussion is closed. Login to edit/delete existing comments.

  • Marcus Turewicz 0

    Thanks Dan.

    Could be worth noting that the .NET wasm and js files have been renamed from “mono.wasm” -> “dotnet.wasm” and “mono.js” -> “dotnet.js”, as per this PR https://github.com/dotnet/aspnetcore/pull/18429.

  • Tony Henrique 0

    Is the Visual Studio 2019 (Preview) – Blazor WebAssembly project template updated automatically?

    • Daniel RothMicrosoft employee 0

      To update or install the Blazor WebAssembly template you just need to run the following command:

      dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.2.0-preview1.20073.1

      After you do that, Visual Studio should pick up the Blazor WebAssembly template and show it alongside the Blazor Server template.

      If you have the old Blazor VSIX installed be sure to uninstall that – it’s no longer needed.

      For more details on getting started see https://docs.microsoft.com/aspnet/core/blazor/get-started

  • Bipin Paul 0

    One more thing I noticed that we need to
    add

    builder.Services.AddOptions();

    in program.cs , if we are using authentication.

    • Geoff Davis 0

      Yes, came across that problem too.

    • Kisa PS 0

      Thx

    • Nikola Nikolov 0

      Thanks

    • Laxman Nagtilak 0

      Thanks.

  • MATTIAS ENGMAN 0

    Very nice! 🙂

  • Howard Richards 0

    Just a note that anyone upgrading older WASM projects with ASP.NET Core server hosting also have a few amendments to make:

    In Startup.cs in the Server app, you may have a reference to the Client.Startup – since this has now been deleted you can change to Client.Program
    e.g. before update:

                app.UseClientSideBlazorFiles<Client.Startup>();
                // etc..
    
                app.UseEndpoints(endpoints =>
                {
                    // other code removed
                    endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
                });
    

    These can be changed to Client.Program

    • Daniel RothMicrosoft employee 0

      Thanks for pointing that out, Howard! I’ve updated the post to add this to the migration steps.

  • Ayyub Ayyubzada 0

    When and how will we able to handle globalization of content(annotations of variables) in blazor web assembly? It is very important but there is not clear solution for that.

  • Sinior Muczaczo 0

    UPDATE: I see that the problem was also reported in a comment that was moderated earlier than mine and issue has already been reported here: https://github.com/dotnet/aspnetcore/issues/18697

    For me great news is “Support for the .NET SignalR client” which allows me to get rid of the need for use eg. SignalR Blazor Extensions (which depends on TypeScript SignalR client).
    But I have encountered problem related to JWT tokens handling… As stated in docs I have modified example from this post – in Pages/Index.razor I have changed source in line:
    .WithUrl(NavigationManager.ToAbsoluteUri(“/chatHub”))
    to:
    .WithUrl(NavigationManager.ToAbsoluteUri(“/chatHub”), opts => { opts.AccessTokenProvider = () => { Console.WriteLine($”{nameof(opts.AccessTokenProvider)} called…”); return Task.FromResult(“XXX”); }; })

    As we can see in Chrome developer console (“Network” tab) provided JWT token (“XXX”) is appended to request headers for Request URL: https://localhost:44319/chatHub/negotiate?negotiateVersion=1 in folowing form:
    authorization: Bearer XXX

    but unfortunately is NOT appended to query string (see “access_token” query string param) or to request headers for Request URL: wss://localhost:44319/chatHub?id=some_id

    I have tried to modify SignalR sample from dotnet-client sample and it worked OK for JS SignalR client and for WPF (Microsoft.AspNetCore.SignalR.Client) client – in both cases we can access token either in headers or query string parameter…

    So it looks that Microsoft.AspNetCore.SignalR.Client used in blazor WASM does not handle JWT auth related scenario properly. Maybe it is becasue “Internet” says that headers can not be modified in Javascript WebSocket API – so when using SignalR C# client in web browser, token generated in AccessTokenProvider should probably by appended to URL instead (similarly like in TypeScript client).

    For now, the only temporary solution seems to be placing the token in the URL:

    .WithUrl(NavigationManager.ToAbsoluteUri(“/chatHub?access_token=XXXX”))

    Is any other better solution or we should wait for official fix?

  • Igor Nesterov 0

    Hi! Thanks for amazing job! But, I have a problem with running project, I created in Ubuntu 19.10 project by this command

    dotnet new blazorwasm -o BlazingPizza.Server

    with this new template version. Everything builds ok, but it can’t start with error:
    Cannot open assembly ‘/home/nesterovi/RiderProjects/BlazingPizza.Server/bin/Debug/netstandard2.1/BlazingPizza.Server.exe’: No such file or directory.

    I tried it In Rider, VS Code, MonoDevelop and everywhere I have the same result.

    Prerequisites:
    Mono, last version from repository and .Net Core 3.1.1 are installed

    Update:
    After all of this I created new solution by this command
    dotnet new blazorwasm -ho -o BlazingPizza
    Then
    dotnet build
    And finally
    dotnet run
    All works fine!

    BUT then, I opened solution in MonoDevelop and showed error as below:
    /home/nesterovi/RiderProjects/BlazingPizza/BlazingPizza/Server/BlazingPizza.Server.csproj: Error NU1201: Project BlazingPizza.Client is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Project BlazingPizza.Client supports: netstandard2.1 (.NETStandard,Version=v2.1) (NU1201) (BlazingPizza.Server)
    /home/nesterovi/RiderProjects/BlazingPizza/BlazingPizza/Server/BlazingPizza.Server.csproj: Error NU1201: Project BlazingPizza.Shared is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Project BlazingPizza.Shared supports: netstandard2.1 (.NETStandard,Version=v2.1) (NU1201) (BlazingPizza.Server)

    It looks like IDEs while does not support new version of Blazor in Linux

    Update 2: In VS Code I built it and run, It seems that it’s problem of MonoDevelop

    • Daniel RothMicrosoft employee 0

      Hi Igor,

      Blazor WebAssembly apps are downloaded to the browser as static files and then executed client-side. There isn’t an executable for Blazor WebAssembly apps that you can just run. We do however provide a dev server to facilitate locally hosting the app on your machine, which is how dotnet run works.

      Blazor WebAssembly apps can also be hosted by an ASP.NET Core app. This is the setup you get when you pass the -ho option when creating the project. The ASP.NET Core app handles serving the static files that make up the Blazor WebAssembly app and enables running .NET code on both sides of the wire. It’s full stack web development with .NET!

      You can build the ASP.NET Core app (the Server project in the generated solution) as an executable that you can just run. Running the exe will start up the ASP.NET Core app which then hosts the Blazor WebAssembly app as static files.

      For Blazor tooling, we support Visual Studio, Visual Studio for Mac, and Visual Studio Code. I’m not aware of any support for Blazor in MonoDevelop.

      I hope this helps!

      • Igor Nesterov 0

        I am not sure, that it helps with my problems with IDEs. But it gives better understanding what happens under the scene=) Thank you!
        Where can I show specific options for webassembly template? Such as “-ho”. Because if not your article I can’t create something like this in Linux. Running template without this option gives only one project.
        Does template have another specific options, or this is “-ho” is only one?

        • Daniel RothMicrosoft employee 0

          You’ll probably need to follow up with the specific IDE owners to understand why Blazor WebAssembly might not be working in those environments. I can really only speak to VS, VS4Mac, and VS Code.

          You can see all of the options for the Blazor WebAssembly template by running dotnet new blazorwasm -h. The -ho option is currently the only supported option, but soon we will be adding options for adding authentication support to the generated project.

          • Igor Nesterov 0

            Daniel, as I noticed that at the first time, VS code automatically generate and add for my solution folder, which calls “.vscode” with tasks.json and launch.json files which contains build tasks. I think that deal on it, because other IDEs don’t create it and(or) don’t understand their format.
            Are this tasks specific for VS Code or are they generated by one of the tool from .Net Core SDK tool?

          • Daniel RothMicrosoft employee 0

            There is specific support in the C# extension for VS Code for enabling tooling support for Razor files. But everything you need to build and run is provided by the .NET Core SDK. The .vscode folder is infrastructure specific to VS Code for wiring up things like debugging.

            Please note the commenting system on this blog is pretty limited, so if you’d like to discuss further you might want to open an issue on GitHub: https://github.com/dotnet/aspnetcore/issues.

  • Øyvind Habberstad 0

    Hi, thanks for this update!

    Regarding “The host also now provides a central configuration instance for the app. The configuration isn’t populated with any data by default, but you can populate it as required in your app.”, where is the config read from? An appsettings.json or is it embedded? And is it somehow possible to have config specific for different environments? Does there exist a more “complete” example? It would have been nice to “bootstrap” the wasm with config from the server, serving the initial request (with config) from an index.cshtml instead of an index.html.

    Thanks in advance!

    • Daniel RothMicrosoft employee 0

      There isn’t any out of the box solution for adding config data currently – we only added the abstraction. You should be able to download a JSON file and plug it into config, but we don’t have a full sample for that yet. I’ve also filed https://github.com/dotnet/aspnetcore/issues/18675 to track having a more complete configuration story out of the box for Blazor WebAssembly.

Feedback usabilla icon