Blazor WebAssembly 3.2.0 Preview 5 release now available

Daniel Roth

Daniel

A new preview update of Blazor WebAssembly is now available! Here’s what’s new in this release:

  • Read configuration during startup
  • Configure HTTP fetch request options
  • Honor existing web.config when publishing
  • Attach tokens to outgoing requests
  • Support for time zones

Get started

To get started with Blazor WebAssembly 3.2.0 Preview 5 install the latest .NET Core 3.1 SDK.

NOTE: Version 3.1.201 or later of the .NET Core SDK is required to use this Blazor WebAssembly release! Make sure you have the correct .NET Core SDK version by running dotnet --version from a command prompt.

Once you have the appropriate .NET Core SDK installed, run the following command to install the updated Blazor WebAssembly template:

dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview5.20216.8

If you’re on Windows using Visual Studio, we recommend installing the latest preview of Visual Studio 2019 16.6. For this preview, you should still install the template from the command-line as described above to ensure that the Blazor WebAssembly template shows up correctly in Visual Studio and on the command-line.

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.2.0 Preview 4 to 3.2.0 Preview 5:

  • Update all Microsoft.AspNetCore.Components.WebAssembly.* package references to version 3.2.0-preview5.20216.8.
  • Update any Microsoft.AspNetCore.Components.WebAssembly.Runtime package references to version 3.2.0-preview5.20216.1.
  • Remove any calls to set WebAssemblyHttpMessageHandlerOptions.DefaultCredentials and instead call SetBrowserRequestCredentials on individual requests (see “Configure HTTP fetch request options” section below).
  • Remove the redirect parameter from calls to TryGetToken on AccessTokenResult.

You’re all set!

Read configuration during startup

Configuration data is now available during app startup in Program.Main using the Configuration property on WebAssemblyHostBuilder. This property can now be used both to add configuration sources and to access the current configuration data.

You can see this feature in action in the project templates when you enable authentication with Azure AD, Azure AD B2C, or an OpenID Connect provider of your choice. The authentication settings are stored in appsettings.json and then read from configuration when the app starts up:

Program.cs

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

        builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

        builder.Services.AddOidcAuthentication(options =>
        {
            // Configure your authentication provider options here.
            // For more information, see https://aka.ms/blazor-standalone-auth
            builder.Configuration.Bind("Local", options.ProviderOptions);
        });

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

appsettings.json

{
  "Local": {
    "Authority": "https:login.microsoftonline.com/",
    "ClientId": "33333333-3333-3333-33333333333333333"
  }
}

Configure HTTP fetch request options

HTTP requests issued from a Blazor WebAssembly app using HttpClient are handled using the browser fetch API. In this release, we’ve added a set of extension methods for HttpRequestMessage that configure various fetch related options. These extension methods live in the Microsoft.AspNetCore.Components.WebAssembly.Http namespace:

HttpRequestMessage extension method Fetch request property
SetBrowserRequestCredentials credentials
SetBrowserRequestCache cache
SetBrowserRequestMode mode
SetBrowserRequestIntegrity integrity

You can set additional options using the more generic SetBrowserRequestOption extension method.

The HTTP response is typically buffered in a Blazor WebAssembly app to enable support for sync reads on the response content. To enable support for response streaming, use the SetBrowserResponseStreamingEnabled extension method on the request.

Honor existing web.config when publishing

When publishing a standalone Blazor WebAssembly app, a web.config is automatically generated for the app that handles configuring IIS appropriately. You can now specify your own web.config in the project, which will get used instead of the generated one.

Attach tokens to outgoing requests

Configuring authentication now adds a BaseAddressAuthorizationMessageHandler as a service that can be used with HttpClient to attach access tokens to outgoing requests. The BaseAddressAuthorizationMessageHandler is preconfigured to make requests to the the app base address. Tokens are acquired using the existing IAccessTokenProvider service. If a token cannot be acquired, an AccessTokenNotAvailableException is thrown. This exception has a Redirect method that can be used to navigate the user to the identity provider to acquire a new token.

The authentication enabled Blazor WebAssembly templates now use IHttpClientFactory to set up an HttpClient with the BaseAddressAuthorizationMessageHandler:

builder.Services.AddHttpClient("BlazorWithIdentityApp1.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorWithIdentityApp1.ServerAPI"));

You can use the configured HttpClient to make authorized requests using a simple try-catch pattern. For example, here’s the updated code in the FetchData component for requesting the weather forecast data:

protected override async Task OnInitializedAsync()
{
    try
    {
        forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
    }
    catch (AccessTokenNotAvailableException exception)
    {
        exception.Redirect();
    }
}

Alternatively, you can simplify things even further by defining a strongly-typed client that handles all of the HTTP and token acquisition concerns within a single class:

WeatherClient.cs

public class WeatherClient
{
    private readonly HttpClient httpClient;

    public WeatherClient(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public async Task<IEnumerable<WeatherForecast>> GetWeatherForeacasts()
    {
        IEnumerable<WeatherForecast> forecasts = new WeatherForecast[0];
        try
        {
            forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        return forecasts;
    }
}

Program.cs

builder.Services.AddHttpClient<WeatherClient>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

FetchData.razor

protected override async Task OnInitializedAsync()
{
    forecasts = await WeatherClient.GetWeatherForeacasts();
}

To make authorized requests to resources not hosted at the app base, use the AuthorizationMessageHandler. The AuthorizationMessageHandler can be configured with the authorized URLs, scopes, and return URL using the ConfigureHandler method.

For example, you can configure an HttpClient to use the AuthorizationMessageHandler like this:

builder.Services.AddSingleton(sp =>
{
    return new HttpClient(sp.GetRequiredService<AuthorizationMessageHandler>()
        .ConfigureHandler(
          new [] { "https://www.example.com/base" },
          scopes: new[] {"example.read", "example.write"}))
        {
           BaseAddress = new Uri("https://www.example.com/base")
        };
});

Alternatively, you can define a custom message handler that inherits from AuthorizationMessageHandler and preconfigures the handler as required.

Support for time zones

Blazor now infers the user’s time zone and uses it in date and time calculations. In addition, APIs on System.TimeZoneInfo that previously returned incomplete results now report correct results.

Help improve the Blazor docs!

Thank you everyone who has taken the time to give feedback on how we can best improve the Blazor docs!

If you haven’t already, please join in with helping us improve the docs by doing the following:

  • As you read the Blazor docs, let us know where we should focus our efforts by telling us if you find a topic helpful or not using the helpfulness widget at the top of each doc page:

    Doc helpfulness

  • Use the Feedback section at the bottom of each doc page to let us know when a particular topic is unclear, inaccurate, or incomplete.

    Doc feedback

  • Comment on our Improve the Blazor docs GitHub issue with your suggestions for new content and ways to improve the existing content.

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!

54 comments

Comments are closed. Login to edit/delete your existing comments