Blazor WebAssembly 3.2.0 Preview 2 release now available

Daniel Roth

Daniel

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

  • Integration with ASP.NET Core static web assets
  • Token-based authentication
  • Improved framework caching
  • Updated linker configuration
  • Build Progressive Web Apps

Get started

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

NOTE: Version 3.1.102 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 update Blazor WebAssembly template:

dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5

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 1 to 3.2.0 Preview 2:

  • Update your package references and namespaces as described below:
    • Microsoft.AspNetCore.Blazor -> Microsoft.AspNetCore.Components.WebAssembly
    • Microsoft.AspNetCore.Blazor.Build -> Microsoft.AspNetCore.Components.WebAssembly.Build
    • Microsoft.AspNetCore.Blazor.DevServer -> Microsoft.AspNetCore.Components.WebAssembly.DevServer
    • Microsoft.AspNetCore.Blazor.Server -> Microsoft.AspNetCore.Components.WebAssembly.Server
    • Microsoft.AspNetCore.Blazor.HttpClient -> Microsoft.AspNetCore.Blazor.HttpClient (unchanged)
    • Microsoft.AspNetCore.Blazor.DataAnnotations.Validation -> Microsoft.AspNetCore.Components.DataAnnotations.Validation
    • Microsoft.AspNetCore.Blazor.Mono -> Microsoft.AspNetCore.Components.WebAssembly.Runtime
    • Mono.WebAssembly.Interop -> Microsoft.JSInterop.WebAssembly
  • Update all Microsoft.AspNetCore.Components.WebAssembly.* package references to version 3.2.0-preview2.20160.5.
  • In Program.cs add a call to builder.Services.AddBaseAddressHttpClient().
  • Rename BlazorLinkOnBuild in your project files to BlazorWebAssemblyEnableLinking.
  • If your Blazor WebAssembly app is hosted using ASP.NET Core, make the following updates in Startup.cs in your Server project:
    • Rename UseBlazorDebugging to UseWebAssemblyDebugging.
    • Remove the calls to services.AddResponseCompression and app.UseResponseCompression() (response compression is now handled by the Blazor framework).
    • Replace the call to app.UseClientSideBlazorFiles<Client.Program>() with app.UseBlazorFrameworkFiles().
    • Replace the call to endpoints.MapFallbackToClientSideBlazor<Client.Program>("index.html") with endpoints.MapFallbackToFile("index.html").

Hopefully that wasn’t too painful!

NOTE: The structure of a published Blazor WebAssembly app has also changed as part of this release, which may require you to update how you deploy your apps. See the “Integration with ASP.NET Core static web assets” section below for details.

Integration with ASP.NET Core static web assets

Blazor WebAssembly apps now integrate seamlessly with how ASP.NET Core handles static web assets. Blazor WebAssembly apps can use the standard ASP.NET Core convention for consuming static web assets from referenced projects and packages: _content/{LIBRARY NAME}/{path}. This allows you to easily pick up static assets from referenced component libraries and JavaScript interop libraries just like you can in a Blazor Server app or any other ASP.NET Core web app.

Blazor WebAssembly apps are also now hosted in ASP.NET Core web apps using the same static web assets infrastructure. After all, a Blazor WebAssembly app is just a bunch of static files!

This integration simplifies the startup code for ASP.NET Core hosted Blazor WebAssembly apps and removes the need to have an assembly reference from the server project to the client project. Only the project reference is needed, so setting ReferenceOutputAssembly to false for the client project reference is now supported.

Building on the static web assets support in ASP.NET Core also enables new scenarios like hosting ASP.NET Core hosted Blazor WebAssembly apps in Docker containers. In Visual Studio you can add docker support to your Blazor WebAssembly app by right-clicking on the Server project and selecting Add > Docker support.

As a result of this change, the structure of the published output of a Blazor WebAssembly app is now more consistent with other ASP.NET Core apps. A Blazor WebAssembly app is now published to the /bin/Release/netstandard2.1/publish/wwwroot folder (a dist folder is no longer generated). To publish a standalone Blazor WebAssembly app as a static site, copy the contents of the published wwwroot folder to your static site host. If the Blazor WebAssembly app is hosted in an ASP.NET Core app, the client Blazor WebAssembly app is published into the wwwroot folder of the published server app just like any other static web asset.

Token-based authentication

Blazor WebAssembly now has built-in support for token-based authentication.

Blazor WebAssembly apps are secured in the same manner as Single Page Applications (SPAs). There are several approaches for authenticating users to SPAs, but the most common and comprehensive approach is to use an implementation based on the OAuth 2.0 protocol, such as OpenID Connect (OIDC). OIDC allows client apps, like a Blazor WebAssembly app, to verify the user identity and obtain basic profile information using a trusted provider.

Using the Blazor WebAssembly project template you can now quickly create apps setup for authentication using:

  • ASP.NET Core Identity and IdentityServer
  • An existing OpenID Connect provider
  • Azure Active Directory

Authenticate using ASP.NET Core Identity and IdentityServer

Authentication for Blazor WebAssembly apps can be handled using ASP.NET Core Identity and IdentityServer. ASP.NET Core Identity handles authenticating users while IdentityServer handles the necessary protocol endpoints.

To create a Blazor WebAssembly app setup with authentication using ASP.NET Core Identity and IdentityServer run the following command:

dotnet new blazorwasm --hosted --auth Individual -o BlazorAppWithAuth1

If you’re using Visual Studio, you can create the project by selecting the “ASP.NET Core hosted” option and the selecting “Change Authentication” > “Individual user accounts”.

Blazor authentication

Run the app and try to access the Fetch Data page. You’ll get redirected to the login page.

Blazor login

Register a new user and log in. You can now access the Fetch Data page.

Fetch data authorized

The Server project is configured to use the default ASP.NET Core Identity UI, as well as IdentityServer, and JWT authentication:

// Add the default ASP.NET Core Identity UI
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

// Add IdentityServer with support for API authorization
services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

// Add JWT authentication
services.AddAuthentication()
    .AddIdentityServerJwt();

The Client app is registered with IdentityServer in the appsettings.json file:

"IdentityServer": {
  "Clients": {
    "BlazorAppWithAuth1.Client": {
      "Profile": "IdentityServerSPA"
    }
  }
},

In the Client project, the services needed for API authorization are added in Program.cs:

builder.Services.AddApiAuthorization();

In FetchData.razor the IAccessTokenProvider service is used to acquire an access token from the server. The token may be cached or acquired without the need of user interaction. If acquiring the token succeeds, it is then applied to the request for weather forecast data using the standard HTTP Authorization header. If acquiring the token silently fails, the user is redirected to the login page:

protected override async Task OnInitializedAsync()
{
    var httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri(Navigation.BaseUri);

    var tokenResult = await AuthenticationService.RequestAccessToken();

    if (tokenResult.TryGetToken(out var token))
    {
        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}");
        forecasts = await httpClient.GetJsonAsync<WeatherForecast[]>("WeatherForecast");
    }
    else
    {
        Navigation.NavigateTo(tokenResult.RedirectUrl);
    }
}

For additional details on using Blazor WebAssembly with ASP.NET Core Identity and IdentityServer see Secure an ASP.NET Core Blazor WebAssembly hosted app with Identity Server

Authenticate using an existing OpenID Connect provider

You can setup authentication for a standalone Blazor WebAssembly using any valid OIDC provider. Once you’ve registered your app with the OIDC provider you configure the Blazor WebAssembly app to use that provider by calling AddOidcAuthentication in Program.cs:

builder.Services.AddOidcAuthentication(options =>
{
    options.ProviderOptions.Authority = "{AUTHORITY}";
    options.ProviderOptions.ClientId = "{CLIENT ID}";
});

You can create a standalone Blazor WebAssembly app that uses a specific OIDC provider for authentication using the following command:

dotnet new blazorwasm --auth Individual --client-id "{CLIENT ID}" --authority "{AUTHORITY}"

For more details on configuring authentication for a standalone Blazor WebAssembly app see Secure an ASP.NET Core Blazor WebAssembly standalone app with the Authentication library

Authenticate using Azure AD & Azure AD B2C

You can also setup Blazor WebAssembly apps to use Azure Active Directory (Azure AD) or Azure Active Directory Business-to-Customer (Azure AD B2C) for authentication. When authenticating using Azure AD or Azure AD B2C authentication is handled using the new Microsoft.Authentication.WebAssembly.Msal library, which is based on the Microsoft Authentication Library (MSAL.js).

To learn how to setup authentication for Blazor WebAssembly app using Azure AD or Azure AD B2C see:

Additional authentication resources

This is just a sampling of the new authentication capabilities in Blazor WebAssembly. To learn more about how Blazor WebAssembly supports authentication see Secure ASP.NET Core Blazor WebAssembly.

Improved framework caching

If you look at the network trace of what’s being download for a Blazor WebAssembly app after it’s initially loaded, you might think that Blazor WebAssembly has been put on some sort of extreme diet:

Blazor network

Whoa! Only 159kB? What’s going on here?

When a Blazor WebAssembly app is initially loaded, the runtime and framework files are now stored in the browser cache storage:

Blazor cache

When the app loads, it first uses the contents of the blazor.boot.json to check if it already has all of the runtime and framework files it needs in the cache. If it does, then no additional network requests are necessary.

You can still see what the true size of the app is during development by checking the browser console:

Blazor loaded resources

Updated linker configuration

You may notice with this preview release that the download size of the app during development is now a bit larger, but build times are faster. This is because we no longer run the .NET IL linker during development to remove unused code. In previous Blazor previews we ran the linker on every build, which slowed down development. Now we only run the linker for release builds, which are typically done as part of publishing the app. When publishing the app with a release build (dotnet publish -c Release), the linker removes any unnecessary code and the download size is much more reasonable (~2MB for the default template).

If you prefer to still run the .NET IL linker on each build during development, you can turn it on by adding <BlazorWebAssemblyEnableLinking>true</BlazorWebAssemblyEnableLinking> to your project file.

Build Progressive Web Apps with Blazor

A Progressive Web App (PWA) is a web-based app that uses modern browser APIs and capabilities to behave like a native app. These capabilities can include:

  • Working offline and always loading instantly, independently of network speed
  • Being able to run in its own app window, not just a browser window
  • Being launched from the host operating system (OS) start menu, dock, or home screen
  • Receiving push notifications from a backend server, even while the user is not using the app
  • Automatically updating in the background

A user might first discover and use the app within their web browser like any other single-page app (SPA), then later progress to installing it in their OS and enabling push notifications.

Blazor WebAssembly is a true standards-based client-side web app platform, so it can use any browser API, including the APIs needed for PWA functionality.

Using the PWA template

When creating a new Blazor WebAssembly app, you’re offered the option to add PWA features. In Visual Studio, the option is given as a checkbox in the project creation dialog:

image

If you’re creating the project on the command line, you can use the --pwa flag. For example,

dotnet new blazorwasm --pwa -o MyNewProject

In both cases, you’re free to also use the “ASP.NET Core hosted” option if you wish, but don’t have to do so. PWA features are independent of how the app is hosted.

Installation and app manifest

When visiting an app created using the PWA template option, users have the option to install the app into their OS’s start menu, dock, or home screen.

The way this option is presented depends on the user’s browser. For example, when using desktop Chromium-based browsers such as Edge or Chrome, an Add button appears within the address bar:

image

On iOS, visitors can install the PWA using Safari’s Share button and its Add to Homescreen option. On Chrome for Android, users should tap the Menu button in the upper-right corner, then choose Add to Home screen.

Once installed, the app appears in its own window, without any address bar.

image

To customize the window’s title, color scheme, icon, or other details, see the file manifest.json in your project’s wwwroot directory. The schema of this file is defined by web standards. For detailed documentation, see https://developer.mozilla.org/en-US/docs/Web/Manifest.

Offline support

By default, apps created using the PWA template option have support for running offline. A user must first visit the app while they are online, then the browser will automatically download and cache all the resources needed to operate offline.

Important: Offline support is only enabled for published apps. It is not enabled during development. This is because it would interfere with the usual development cycle of making changes and testing them.

Warning: If you intend to ship an offline-enabled PWA, there are several important warnings and caveats you need to understand. These are inherent to offline PWAs, and not specific to Blazor. Be sure to read and understand these caveats before making assumptions about how your offline-enabled app will work.

To see how offline support works, first publish your app, and host it on a server supporting HTTPS. When you visit the app, you should be able to open the browser’s dev tools and verify that a Service Worker is registered for your host:

image

Additionally, if you reload the page, then on the Network tab you should see that all resources needed to load your page are being retrieved from the Service Worker or Memory Cache:

image

This shows that the browser is not dependent on network access to load your app. To verify this, you can either shut down your web server, or instruct the browser to simulate offline mode:

image

Now, even without access to your web server, you should be able to reload the page and see that your app still loads and runs. Likewise, even if you simulate a very slow network connection, your page will still load almost immediately since it’s loaded independently of the network.

To learn more about building PWAs with Blazor, check out the documentation.

Known issues

There are a few known issues with this release that you may run into:

  • When building a Blazor WebAssembly app using an older .NET Core SDK you may see the following build error:

    error MSB4018: The "ResolveBlazorRuntimeDependencies" task failed unexpectedly.
    error MSB4018: System.IO.FileNotFoundException: Could not load file or assembly '\BlazorApp1\obj\Debug\netstandard2.1\BlazorApp1.dll'. The system cannot find the file specified.
    error MSB4018: File name: '\BlazorApp1\obj\Debug\netstandard2.1\BlazorApp1.dll' 
    error MSB4018:    at System.Reflection.AssemblyName.nGetFileInformation(String s)
    error MSB4018:    at System.Reflection.AssemblyName.GetAssemblyName(String assemblyFile)
    error MSB4018:    at Microsoft.AspNetCore.Components.WebAssembly.Build.ResolveBlazorRuntimeDependencies.GetAssemblyName(String assemblyPath)
    error MSB4018:    at Microsoft.AspNetCore.Components.WebAssembly.Build.ResolveBlazorRuntimeDependencies.ResolveRuntimeDependenciesCore(String entryPoint, IEnumerable`1 applicationDependencies, IEnumerable`1 monoBclAssemblies)
    error MSB4018:    at Microsoft.AspNetCore.Components.WebAssembly.Build.ResolveBlazorRuntimeDependencies.Execute()
    error MSB4018:    at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
    error MSB4018:    at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask)
    

    To address this issue, upgrade to version 3.1.102 or later of the .NET Core 3.1 SDK.

  • You may see the following warning when building from the command-line:

    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
    

    This issue will be fixed in a future update to the .NET Core SDK. To workaround this issue, add the <DisableImplicitComponentsAnalyzers>true</DisableImplicitComponentsAnalyzers> property to the project file.

  • The following error may occur when publishing an ASP.NET Core hosted Blazor app with the .NET IL linker disabled:

    An assembly specified in the application dependencies manifest (BlazorApp1.Server.deps.json) was not found
    

    This error occurs when assemblies shared by the server and Blazor client project get removed during publish (see https://github.com/dotnet/aspnetcore/issues/19926).

    To workaround this issue, ensure that you publish with the .NET IL linker enabled. To publish with the linker enabled:

    • Publish using a Release build configuration: dotnet publish -c Release. The .NET IL linker is automatically run for Release builds, but not for Debug builds.
    • Don’t set BlazorWebAssemblyEnableLinking to false in your client project file.

    If you’re hitting issues running with the linker disabled, you may need to configure the linker to preserve code that is being called using reflection. See https://docs.microsoft.com/aspnet/core/host-and-deploy/blazor/configure-linker for details.

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!

129 comments

Leave a comment

  • Avatar
    John Barrett

    https://github.com/dotnet/aspnetcore/issues/19752

    There seems to be a nuget package missing -Step to reproduce:

    Assuming latest SDL + template installed (VS2019 16.5.0 preview 5.0)

    Create new Project
    Select Blazor Template
    Choose WASM, change Auth to individual user accounts, tick Hosted
    Click Build

    Expected
    Build Succeeded

    Actual

    Severity Code Description Project File Line Suppression State
    Error NU1101 Unable to find package Microsoft.AspNetCore.Components.WebAssembly.Runtime. No packages exist with this id in source(s): Microsoft Visual >Studio Offline Packages, nuget.org BlazorApp4.Client C:\Users\xxxx\source\repos\BlazorApp4\BlazorApp4\Client\BlazorApp4.Client.csproj 1

  • Mitchell Currey
    Mitchell Currey

    Hi Daniel,

    Thanks for the very descriptive post!
    Great stuff here!

    Just wanted to note the typos in the “Upgrade an existing project” section.
    Your references to “Microsoft.AspNetCore.Components.WebAsssembly” have an extra s in WebAsssembly.
    This caught me out when copy pasting!

    Thanks.

  • Ben Hayat
    Ben Hayat

    A huge thanks to Dan and Blazor team, for integrating Auth (IdentityServer & Azure B2C) with Blazor WASM.

    This will now allow companies to consider building LoB Apps with Blazor WASM with full security.
    Great job guys!

    Thanks!
    ..Ben

  • Avatar
    Sebastian Stehle

    Do you have plans for bundling?
    Today big web apps have sometimes hundred of dependencies and having to download hundreds of dlls might be not the best idea.
    Furthermore are there any plans for lazy loading and creating independent chunks for feature modules in bigger apps?

    • Ben Hayat
      Ben Hayat

      I also have same questions. Suppose we have an app that supports two types of users. Basic and PRO users.
      After a user logs in and the client app determines what type of user she is, then we would like to decide what modules to load or not to load depending on the user type. For example, Basic users might be 80% of our users, so we don’t want 80% of users to load modules that only belong to PRO users (20%).

      We could wait till the .Net 5 to be released for this feature, but on-demand and lazy loading are very critical on the success of our apps acceptance by general public.

      Or perhaps MSFT could provide a sound guidelines that we can follow to break the app physically, especially for Mobile users, so we can achieve similar results.
      Thanks!
      ..Ben

      • Daniel Roth
        Daniel Roth

        Adding support for lazy loading of app areas is on our backlog: https://github.com/dotnet/aspnetcore/issues/5465. We don’t expect to get to it for the Blazor WebAssembly release in May, so the earliest we’d get to this is for .NET 5.

        We think though that you may be surprised at how large your app needs to get before this becomes a problem. .NET IL is a compact format, so it takes a lot of app code before this becomes a problem. You can also use the .NET IL linker to remove unneeded from dependencies. If you’re hitting issues where your app is getting too large and you think splitting it up in this way would help please let us know as we’d like to understand better through concrete examples what large apps like this look like.

        For full modularity support I would also suggest taking at the Oqtane project: https://www.oqtane.org/.

        • Avatar
          Sebastian Stehle

          The loading times are already pretty long, takes 4-5 seconds on my machine. Not a big problem for something like an Office365 but for E-Commerce sites it could be better. I think one part of the success stories of react and angular is that there are big companies who use these frameworks for their own products, something that is still pending for Blazor afaik.

  • Avatar
    Göran Halvarsson

    Thanks for this lovely release – Blazor WebAssembly 3.2.0 Preview 2.
    I have some issues though, I have the latest Visual Studio 2019 (Version 16.4.6)
    So when I create a blazor webassembly project( as hosted) and then build it I get the following error:

    Error MSB4018 The “ResolveTargetingPackAssets” task failed unexpectedly.
    System.IO.DirectoryNotFoundException: Could not find a part of the path ‘C:\Program Files\dotnet\packs\NETStandard.Library.Ref\2.1.0\data\FrameworkList.xml’.
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
    at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
    at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
    at System.Xml.XmlTextReaderImpl.FinishInitUriString()
    at System.Xml.XmlTextReaderImpl..ctor(String uriStr, XmlReaderSettings settings, XmlParserContext context, XmlResolver uriResolver)
    at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
    at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)

    The folder C:\Program Files\dotnet\packs\NETStandard.Library.Ref\2.1.0 is also empty.
    Very strange, I have never seen this before

    Any ideas?

  • Shang Jeng Tung
    Shang Jeng Tung

    Hi

    New update include IdentityServer is very good news for me, I try new project template immediately, But when I add Identity Scaffold to override login page,

    Project Client theme is all disapper and show An unhandled error has occurred. Reload đź—™ without any message in console , but login page show correctly.

    Any Idea for this error?

  • Avatar
    James Hancock

    Still needs lazy loading of routes to be viable in a production scenario of a site with hundreds of pages, otherwise the first load size just keeps growing and growing. Given that this is not happening until .NET 5, this release is little more than a show case.

    • Daniel Roth
      Daniel Roth

      Hi James. Yup, it’s on our backlog: https://github.com/dotnet/aspnetcore/issues/5465. We just haven’t got to it yet. The reason we haven’t prioritized it higher is that we believe for most apps the download size will be dominated by the size of the runtime and core framework libraries. The size impact of each additional page is typically pretty small, so lazy loading often won’t have much of an impact on the initial load. That said, we understand that apps can get really big and this is something we play to address in a future release.

      • Avatar
        James Hancock

        I think you guys need to check again because your target audience is Enterprise LOB for the most part with this. The upfront is still way to large for publicly facing websites (to say nothing of SEO which right now appears to be a non-starter). We were considering using Blazor for our logged on user area until we realized this major issue.

        We have an Angular 9.1 website. It’s initial load with all of the libraries we use (Bootstrap, CSS, SignalR, whatever the requested page the user asks for for kendo ui) + our content is about 1.2 megs gziped to the user (not counting images etc). The entire size of the site with all pages is about 31 megs gziped. It isn’t a huge site, think pluralsite size.

        Now, I realize that binary compilation of Blazor will make it smaller, but gzip will bring it pretty close to what Blazor will produce.

        In Blazor, your target audience is going to be faced with asking people to download 25 or megs of stuff just to see first render, or not use Blazor.

        And worse, they’ll happily code along, then after many days and weeks, realize it’s getting huge and realize that there is no way to fix it and be faced with a choice of waiting until November or tossing Blazor and never touching it again and being really angry at Microsoft.

        This is exactly the type of decision making that gets Microsoft in trouble. You’re use cases are out of wack. (well that and reinventing everything over and over again like Skype, .NET Core nea .net 5, WPF, Silverlight, UWP, on and on causing you to fall behind in the market and lose one you owned in Skype to Zoom, an inferior product, but Skype hasn’t actually improved at all to the end user since Microsoft bought it…)

        You guys need to seriously rethink the decision not to get this into this release. If you don’t, you’re at best going to have a bunch of angry devs, and more likely going to have a ton of devs that decide to use something else for another 6 months of Microsoft falling behind without an SPA. (and this is after you lost the lead from knockout, and Durandal to angular,react,vue in the first place because of reinventing the wheel instead of incrementally improving Durandal and making it a real product within MS since it’s still better today than Angular 9 is in many ways. Yes I know it was done by Rob, but he’s now an MS employee or was, and you could have easily brought all of it in house and Angular lost it’s lead to React and begat Vue because they decided to do a complete rewrite instead of incremental improvement to where they are now with the same consequences as every time MS does this.)

        And this is emblematic of the problem with Blazor Mobile. Instead of focusing on your true competitor, Flutter, you’re obsessed with yesterday’s tech and copying React Native so we’re getting wrappers around Xamarin, instead of a native rendering engine that works across mobile, web, and desktop like Flutter. If the effort was focused where it needs to be, the Xamarin infrastructure and Azure cloud for doing iOS compiles and remote simulators so that windows devs didn’t have to own a mac, would have been a huge advantage and would have smoked flutter and created a compelling story. Instead we’re getting something that anyone in the space isn’t asking for. Sanderson obviously saw this because his POC on the subject used the Flutter rendering engine with Blazor. But then somewhere along the lines it got hijacked into the mess it is, and that has enormous consequences to the success of Windows as a whole, but Duo and Neo specifically. And given that Windows has been given one last shot moving it all under Surface’s boss, this should be enormously worrying.

        It’s really sad to see Blazor’s enormous potential squandered, when it could have been Microsoft’s ticket back into end user UX/UI development and freed Microsoft from the handcuffs of xaml which is enormously hated based on the surveys from devs.

  • Avatar
    Brady Marston

    I understand that you’re maintaining several SPA templates at this point and the Razor pages approach allows for a one size fits all solution, but is there any chance of a template with an individual accounts authentication UI implemented entirely in Blazor?

  • Rod Macdonald
    Rod Macdonald

    I wanted to spin up the PWA option out of the box using the default counter/weather data app. The PWA checkbox option is there, so I assume all’s good with the latest SDK, but the ‘add’ button doesn’t appear in the URL. What am I doing wrong? Thank you.

    …ah, Edge is in dark mode and the add ‘+’ button, just like the favourites star, is far right of the address bar and difficult to see! All good now.

  • Avatar
    Marcius Nery

    I published the application and when accessing it is showing the following error.

    HTTP Error 500.31 – ANCM Failed to Find Native Dependencies
    Common solutions to this issue:
    The specified version of Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
    Troubleshooting steps:
    Check the system event log for error messages
    Enable logging the application process’ stdout messages
    Attach a debugger to the application process and inspect

    In the event viewer i found the description:
    Could not find ‘aspnetcorev2_inprocess.dll’. Exception message: Error: An assembly specified in the application dependencies manifest (DVCE.Server.deps.json) was not found: package: ‘Blazored.Modal’, version: ‘3.1.2’ path: ‘lib/netstandard2.0/Blazored.Modal.dll’
    Process Id: 11560.
    File Version: 13.1.20018.2. Description: IIS ASP.NET Core Module V2. Commit: c3acdcac86dad91c3d3fbc3b93ecc6b7ba494bdc

      • Avatar
        Craig Johnson

        Daniel,

        I’d like to add that we are having the same issue. At first we thought it was an IIS issue but it is not.

        Steps to Reproduce:

        Create a WebAssembly app with ASP.Net Core hosting (generates the .Client, .Server, .Shared)
        Add a reference (e.g., Blazored.Modal) to the .Client project
        Run dotnet publish -c Release
        Go to the publish folder and run the .Server.exe

        Error immediately occurs that it is unable to find the assembly (looking in /lib/netstandard2.0/Blazored.Modal.dll)

        I also attempted PublishWithAspNetCoreTargetManifest = false with no effect

      • Avatar
        Michael Spranger

        Hi Daniel,

        I too have hit this problem. The third party dependency Blazored.Modal’.dll is missing, as well as several others (list is not complete):
        Google.Protobuf
        Grpc.Core.Api
        Grpc.Net.Client.Web
        Grpc.Net.Client
        Grpc.Net.Common
        Microsoft.AspNetCore.Components.WebAssembly

        I publish with dotnet publish, followed by Compress-Archive and Publish-AzWebapp.
        In my case the cause is that dotnet publish -c Debug omits these dependencies while including others, whereas dotnet publish -c Release adds all of them correctly to the publish folder. I do not see a reason for this different behavior, but with the latter option the deployment to AppService works fine.

  • Avatar
    Zach Reynolds

    Really enjoying the previews for Blazor WASM! I swapped out my service-worker.js with the one created through the template, and all was working quite well until I went to publish. The onInstall function in service-worker-published.js doesn’t seem to like the { integrity: asset.hash } aspect of the Request. All of my dlls in the service-worker-assets.js file produce a SHA-256 mismatch and Chrome denies loading of the resource.

    .map(asset => new Request(asset.url, { integrity: asset.hash }));

    If I change to the following it works fine, but then I lose the integrity check.

    .map(asset => new Request(asset.url));

    example error: Failed to find a valid digest in the ‘integrity’ attribute for resource ‘https://foo.bar/_framework/_bin/Microsoft.AspNetCore.Components.Web.dll’ with computed SHA-256 integrity ‘vCEa3gqoQS5aAN0wq+fGIjUUcKKPTh068Y8QMy0/Y1g=’. The resource has been blocked.

    Am I completely overlooking something simple?

  • Daniel Fawcett
    Daniel Fawcett

    I’ve updated my current web assembly project as instructed and i’m getting this build error:

    System.InvalidOperationException: Unable to resolve service for type ‘Microsoft.AspNetCore.ResponseCompression.IResponseCompressionProvider’ while attempting to activate ‘Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware’.
    at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
    at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
    at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.c__DisplayClass4_0.b__0(RequestDelegate next)
    at Microsoft.AspNetCore.Builder.ApplicationBuilder.Build()
    at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
    The thread 0xc85c has exited with code 0 (0x0).
    Exception thrown: ‘System.InvalidOperationException’ in System.Private.CoreLib.dll
    An unhandled exception of type ‘System.InvalidOperationException’ occurred in System.Private.CoreLib.dll
    Unable to resolve service for type ‘Microsoft.AspNetCore.ResponseCompression.IResponseCompressionProvider’ while attempting to activate ‘Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware’.

    Any help would be greatly appreciated

  • Avatar
    Jean Transcène

    Great job guys. Love my experience with Blazor so far.
    I noticed the disappearance of startup.cs from the client project and I was wondering how to get access to IServiceCollection and services.AddScoped<>() client side?

  • Avatar
    Yadel Lopez

    Hey Dan. I have updated all packages as recommended above. However, I am receiving the following error message. I’ve tried repairing, restarting, everything with no luck.
    Package Microsoft.AspNetCore.Components.WebAssembly.Server 3.2.0-preview2.20160.5 is not compatible with netstandard2.1 (.NETStandard,Version=v2.1). Package Microsoft.AspNetCore.Components.WebAssembly.Server 3.2.0-preview2.20160.5 supports: netcoreapp3.1 (.NETCoreApp,Version=v3.1)

    • Daniel Roth
      Daniel Roth

      Hi Yadel. It sounds like you’re referencing the Microsoft.AspNetCore.Components.WebAssembly.Server package from your client Blazor WebAssembly project. Blazor WebAssembly projects target .NET Standard 2.1. But this package should only be referenced from an ASP.NET Core project that targets .NET Core 3.1. The package is used to integrate Blazor WebAssembly into an ASP.NET Core app. We often call this setup an ASP.NET Core hosted Blazor WebAssembly app. If you’re trying to host a Blazor WebAssembly app in ASP.NET Core then move this package reference to your Server project. If you just want a standalone Blazor WebAssembly app that you intend to deploy as a static site, you can just remove this package reference. I hope this helps!

  • Avatar
    Curious Drive

    Some observations while upgrading from Preview 1 to Preview 2
    var builder = WebAssemblyHostBuilder.CreateDefault(args); was throwing an error after upgrading the references
    -> I had to change the namespace to using Microsoft.AspNetCore.Components.WebAssembly.Hosting; that I was using in Program.cs
    UseWebAssemblyDebugging and UseBlazorFrameworkFiles were throwing an error
    -> because it wasn’t mentioned to upgrade server references to
    PackageReference Include=”Microsoft.AspNetCore.Components.WebAssembly.Server” Version=”3.2.0-preview2.20160.5″

  • Avatar
    Kurt Koller

    Fantastic step forward!

    The only issue remaining…

    If compiling/loading changes to .wasm instead of *.dll files so evil evil antivirus (and dumb corporate firewall rules) stop being an issue, we’re 100% in business!

    Great work and the migration instructions are on point through the last two versions, which is HIGHLY apprecaited!

    • Daniel Roth
      Daniel Roth

      Hi Kurt. If you’re seeing issues with the downloaded .dlls being dropped, you can try renaming the files as a workaround. We made some changes in this release to make renaming the files easier to do. See https://github.com/dotnet/aspnetcore/issues/5477#issuecomment-599148931 for instructions on how to do this. Could you give this approach a try and let us know on the GitHub issue if you’re still seeing issues? Thanks!

      • Avatar
        Kurt Koller

        Hi Daniel,

        That’s a heck of a quick reply. I got an email (I’m following that issue) and I came here to express joy that it was updated and lo and behold you’ve made a comment here as well. I ran the script (I develop on Windows, but I deploy from a Linux environment to another Linux environment, so I used the Linux script provided) and it deployed with the new names, and when loading the page it seems to be loading the files with the new extensions fine, and the app works. I will follow up on the github issues once I get a test done on a machine with the AV and the machine with the firewall issue. The AV machine will be easy enough, but the “dumb corporate firewall” will be an issue because their office is on hiatus due to the pandemic situation, so I’ll follow up on that once they figure out what’s up and settle in.

        Thanks a trillion for the speedy speedy reply!

  • Avatar
    Lucas Elzinga

    Is there any location that we can see the coming updates, I have tried to find a location that I can always visit to see the current roadmap for future updates.. I know there is a larger update coming out in May but how can I find out what is planned to be within that release?

  • Avatar
    Ismel MartĂ­nez DĂ­az

    Hello.

    I try to use the generated files in a test python host.

    First I create a folder blazor-test and put these files into it

    _framework (folder)
    css (folder)
    sample-data (folder)
    favicon.ico
    index.html

    Then, I run the command python -m http.server 8000 to host the files using a lightweight python http server.

    So, next step I load the page http://localhost:8000 into a browser.

    The SPA load fine !!! All ok.

    I can navigate to /, to /counter and to /fetchdata.

    But, when I want to reload the /fetchdata page or the /counter page, I get 404 File not found page.

    Do you think use the url hash #! or # to solve this problem?

    Thanks.

  • Jonny Olliff-Lee
    Jonny Olliff-Lee

    Hi, only just saw this post thanks to a colleague. Thank you to the Blazor team for more awesome improvements with this version!

    After upgrading though I’ve ran an into an issue at build time. I upgraded the packages and built, all good. Then I ran a git clean -xdf, and built and got the following error:

     Fatal error in Mono IL Linker
    C:\Users\jonathan.ollifflee\.nuget\packages\microsoft.aspnetcore.components.webassembly.build\3.2.0-preview2.20160.5\targets\Blazor.MonoRuntime.targets(245,5): error : Unhandled exception. Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'obj\Release\netstandard2.1\BlazorTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' [D:\dev\BlazorTest\src\BlazorTest\BlazorTest.csproj]
       ---> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'obj\Release\netstandard2.1\BlazorTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
         at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
         at Mono.Linker.AssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)
         at Mono.Linker.LinkContext.Resolve(IMetadataScope scope)
         at Mono.Linker.LinkContext.Resolve(IMetadataScope scope)
         at Mono.Linker.LinkContext.Resolve(String name)
         at Mono.Linker.Steps.ResolveFromAssemblyStep.Process()
         at Mono.Linker.Steps.BaseStep.Process(LinkContext context)
         at Mono.Linker.Pipeline.ProcessStep(LinkContext context, IStep step)
         at Mono.Linker.Pipeline.Process(LinkContext context)
         at Mono.Linker.Driver.Run(ILogger customLogger)
         at Mono.Linker.Driver.Execute(String[] args, ILogger customLogger)
         at Mono.Linker.Driver.Main(String[] args)
    C:\Users\jonathan.ollifflee\.nuget\packages\microsoft.aspnetcore.components.webassembly.build\3.2.0-preview2.20160.5\targets\Blazor.MonoRuntime.targets(245,5): error : ILLink failed with exit code -532462766. [D:\dev\BlazorTest\src\BlazorTest\BlazorTest.csproj]

    Nothing gets outputed to the bin folder (which is why the DLL can’t be found). If I revert back to a previous commit, and rebuild all is well again.

    Any thoughts?

  • Nikola Nikolov
    Nikola Nikolov

    Hallo Daniel,

    Up to now i have used Role Based Authorisation as per the example provided by Chris Sainty – https://chrissainty.com/securing-your-blazor-apps-configuring-role-based-authorization-with-client-side-blazor/ – and the same has worked really well.

    Now I have updated to the new version of blazor.net and I really couldn figgure out how to have the Roles worked again with IdentityServer4.

    I will be verry gratefull If you provide me with an example or link how to implement Roles as well.

    Thanks in advance.

    Nikola

      • Nikola Nikolov
        Nikola Nikolov

        Hallo Daniel and thank you very much for the quick response. At the end it have worked, but I have used Chris Santy ApiAuthenticationProvider instead of the new provided ApiAthenticationProvider with following settings in Startup.

        if (!_environment.IsDevelopment())
        {
        var cert = new X509Certificate2(@"cert/cert.pfx", "password");
        services.AddCertificateManager();
        var keysFolder = Path.Combine(_environment.ContentRootPath, "Keys");

        services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
        .SetApplicationName("myProject")
        .SetDefaultKeyLifetime(TimeSpan.FromDays(90)).ProtectKeysWithCertificate(cert);
        }

        services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
        options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = false)
        .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();
        services.AddMvc();
        services.AddIdentityServer()
        .AddApiAuthorization&lt;ApplicationUser, ApplicationDbContext&gt;();

        //services.AddAuthentication()
        // .AddIdentityServerJwt();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =&gt;
        {
        options.TokenValidationParameters = new TokenValidationParameters
        {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration["JwtIssuer"],
        ValidAudience = Configuration["JwtAudience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]))
        };
        }).AddIdentityServerJwt();

        services.AddControllersWithViews();
        services.AddRazorPages();
        }

      • Avatar
        Juergen

        Hi Daniel,
        yesterday, in asp.net community standup, Steve Sanderson shew a project “MyAppWithIdentityRoles”, which seems to be exactly what we need. Might it be possible, to get a look on its implementation?
        Thanks, for your great work!

        • Daniel Roth
          Daniel Roth

          Hi Juergen,

          We’ll get this better documented soon, but for now here’s how you use roles with ApiAuthorization + Blazor WebAssembly:

          • Configure Identity to use roles by calling AddRoles

            services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles()
            .AddEntityFrameworkStores();

          • Configure identity server to put the role claim into the id token and the access token and prevent the default mapping for roles in the JwtSecurityTokenHandler.

            services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
            options.IdentityResources["openid"].UserClaims.Add("role");
            options.ApiResources.Single().UserClaims.Add("role");
            });

            // Need to do this as it maps "role" to ClaimTypes.Role and causes issues
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");

          • On your blazor application use [Authorize(Roles = "admin")] or any other role your app defines.
          • On your protected resource APIs use [Authorize(Roles = "admin")] or any other role your app defines.

          I hope this helps!

  • Avatar
    Kai Peng

    Great and really needed new features!

    I am working on a test blazor wasm project which needs authentication. Want to use the new authentication feature for sure. Those code snippets in Javier and Luke’s article is great: https://docs.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/standalone-with-authentication-library?view=aspnetcore-3.1

    Is there anywhere on GitHub we can download the complete code examples with these new features? Thanks!

    • Daniel Roth
      Daniel Roth

      Hi Endy. Everything still seems to be on track for May. We’re grateful that so far everyone on the team seems to be healthy and well, and folks are all working hard from home to get the final touches on Blazor WebAssembly done for the May release.

      We also understand that not everyone has been as fortunate. Just this past weekend, an elderly neighbor and close friend to my family passed away from COVID-19 after a week long struggle. Just this morning we found out a that the middle aged daughter of a family friend was in the hospital recovering from a cancer surgery, but then contracted COVID-19, which ended her promising recovery. It really struck close to home (in a very literal sense) just how serious this whole situation is.

      So stay safe everyone! Take appropriate precautions and we’ll get through this.

      • Rod Macdonald
        Rod Macdonald

        Hi Daniel, these are very hard hitting things to hear indeed. The situation is accelerating towards us all – we’re very close to a complete lockdown in the UK. I’ve had to pack in my work for now (new business, disaster), and to lift spirits and get working on something positive, wondered if there was any chance of bringing Build forwards assuming the sessions will ultimately be online?

        Of course even doing something within the confines of a recording studio might be too challenging.

  • Avatar
    Stian Kraggerud

    Hi,

    After upgrading to 3.2.0, all links stopped working. The url changes in the browser, but nothing happens. There is no error in the console when I press a link.
    If I enter the path to the page directly in the browser the page loads, but not when I use NavLink component.

    Any idea?

    Regards
    Stian

  • Wade Balzer
    Wade Balzer

    I don’t know if this is just me, but on two machines running VS 2019 v16.4.6, I create a Blazor WebAssembly project with Individual User Accounts option, ASP.Net Core Hosted, and PWA options checked. I’m using ASP.Net Core 3.1.200. Doing nothing more than just running the application (IIS Express), when I click the Register Link at the top of the page, the page says… Checking login state…. with an “An unhandled error has occurred. Reload” at the bottom.

    WASM: Unhandled exception rendering component:
    blazor.webassembly.js (1,35601)
    WASM: Microsoft.JSInterop.JSException: Invalid calling object
    blazor.webassembly.js (1,35601)
    WASM: TypeError: Invalid calling object
    blazor.webassembly.js (1,35601)
    WASM:    at Anonymous function (https://localhost:44308/_framework/blazor.webassembly.js:1:9733)
    blazor.webassembly.js (1,35601)
    WASM:    at Promise (native code)
    blazor.webassembly.js (1,35601)
    WASM:    at e.jsCallDispatcher.beginInvokeJSFromDotNet (https://localhost:44308/_framework/blazor.webassembly.js:1:9703)
    blazor.webassembly.js (1,35601)
    WASM:    at _mono_wasm_invoke_js_marshalled (https://localhost:44308/_framework/wasm/dotnet.3.2.0-preview2.20159.2.js:1:162911)
    blazor.webassembly.js (1,35601)
    WASM:    at Module[_mono_wasm_invoke_method] (https://localhost:44308/_framework/wasm/dotnet.3.2.0-preview2.20159.2.js:1:187078)
    blazor.webassembly.js (1,35601)
    WASM:    at BINDING.call_method (https://localhost:44308/_framework/wasm/dotnet.3.2.0-preview2.20159.2.js:1:150813)
    blazor.webassembly.js (1,35601)
    WASM:    at Anonymous function (https://localhost:44308/_framework/wasm/dotnet.3.2.0-preview2.20159.2.js:1:153153)
    blazor.webassembly.js (1,35601)
    WASM:    at beginInvokeDotNetFromJS (https://localhost:44308/_framework/blazor.webassembly.js:1:37610)
    blazor.webassembly.js (1,35601)
    WASM:    at s (https://localhost:44308/_framework/blazor.webassembly.js:1:8432)
    blazor.webassembly.js (1,35601)
    WASM:    at e.invokeMethodAsync (https://localhost:44308/_framework/blazor.webassembly.js:1:9502)
    blazor.webassembly.js (1,35601)
    WASM:   at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x2cb9260 + 0x0002c> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    WASM:   at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync (Microsoft.JSInterop.IJSRuntime jsRuntime, System.String identifier, System.Object[] args) <0x2aa1508 + 0x000e4> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    WASM:   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticatorViewCore`1[TAuthenticationState].OnParametersSetAsync () <0x2d5f528 + 0x00550> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    WASM:   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion (System.Threading.Tasks.Task task) <0x2bffdd8 + 0x000e6> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    WASM:   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2a11168 + 0x001fc> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    WASM:   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2c00918 + 0x000c2> in <filename unknown>:0 
    blazor.webassembly.js (1,35601)
    

    The Login link works just fine, and the Register link on the server page works fine. Returning back to the Client app, clicking my email address to take me to a profile page… that is also broken.

    I am assuming the problem lies in the new tag…

    <RemoteAuthenticatorView Action="@Action" />

    Thanks,

  • Avatar
    Miku Kaito

    Strange issue after updating I get with my own app and also with a fresh one made off the PWA Webassembly template:

    blazor Loaded 6.03 MB resourcesThis application was built with linking (tree shaking) disabled. Published applications will be significantly smaller.

    WASM: System.TypeLoadException: Could not resolve type with token 01000018 from typeref (expected class ‘System.Threading.Tasks.Task’ in assembly ‘System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’)
    WASM: at (wrapper managed-to-native) System.Reflection.MonoMethodInfo.get_parameter_info(intptr,System.Reflection.MemberInfo)
    WASM: at System.Reflection.MonoMethodInfo.GetParametersInfo (System.IntPtr handle, System.Reflection.MemberInfo member) in :0
    WASM: at System.Reflection.RuntimeMethodInfo.GetParameters () in :0
    WASM: at System.Reflection.MethodBase.GetParametersNoCopy () in :0
    WASM: at System.RuntimeType.FilterApplyMethodBase (System.Reflection.MethodBase methodBase, System.Reflection.BindingFlags methodFlags, System.Reflection.BindingFlags bindingFlags, System.Reflection.CallingConventions callConv, System.Type[] argumentTypes) in :0
    WASM: at System.RuntimeType.FilterApplyMethodInfo (System.Reflection.RuntimeMethodInfo method, System.Reflection.BindingFlags bindingFlags, System.Reflection.CallingConventions callConv, System.Type[] argumentTypes) in :0
    WASM: at System.RuntimeType.GetMethodCandidates (System.String name, System.Int32 genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.CallingConventions callConv, System.Type[] types, System.Boolean allowPrefixLookup) in :0
    WASM: at System.RuntimeType.GetMethodImplCommon (System.String name, System.Int32 genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) in :0
    WASM: at System.RuntimeType.GetMethodImpl (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) in :0
    WASM: at System.Type.GetMethod (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) in :0
    WASM: at System.Type.GetMethod (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) in :0
    WASM: at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.FindUnderlyingEntrypoint (System.Reflection.Assembly assembly) in :0
    WASM: at Microsoft.AspNetCore.Components.WebAssembly.Hosting.EntrypointInvoker.InvokeEntrypoint (System.String assemblyName, System.String[] args) in :0

    Googled and tried things for a long time, reinstalled .net 3.2.200 x86 and x64. Might just give up on it for now or reinstall everything, seems to be a very unique issue.

  • Avatar
    Lucas Elzinga

    Is there any point that Blazor Web Assembly will move away from the MVC server side scaffold authentication pages? It would be nice if the scaffolding had a Blazor configured authentication process using the tokens and api instead of having 2 different style within the same project. I know it probably isn’t high priority or anything but it would be nice to see a full end to end authentication/authorization built in razor components.

  • Avatar
    Osman Taskiran

    Hi Daniel,

    Preview 2 issues annoying.
    Could you please add this version issues to the Known Issues section. Everybody losing their time!
    for example: IIS – Azure Win App Service 500.31
    Blazor is your product, Azure is your product, Windows is your product, IIS is your product, but there is no any attention.

    I don’t need to read all posts before deployment.

  • ice denis
    ice denis

    I have m.b a stubid question but i really cant find the solution for it :
    in old version my Programm.cs on clinet side was looking like this :
    public class Program
    {
    public static void Main(string[] args)
    {
    CreateHostBuilder(args).Build().Run();
    }

        public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
            BlazorWebAssemblyHost.CreateDefaultBuilder()
                .UseBlazorStartup<Startup>();
    }
    

    new Version i made it like this >
    public class Program
    {
    public static async Task Main(string[] args)
    {
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add(“app”);

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

    and now what do i do with this Setup on the Client side:?
    public class Startup
    {
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddStorage();
    services.AddToaster(config =>
    {
    config.PositionClass = Defaults.Classes.Position.TopRight;
    config.PreventDuplicates = true;
    config.NewestOnTop = false;
    });
    }

         public void Configure(IComponentsApplicationBuilder app)
        {
            app.AddComponent<App>("app");
        }
    
    }
    
  • Dario Granich
    Dario Granich

    Hi,

    After updating to this latest version and fixing all the issue, I am still seeing the following error

    Conflicting assets with the same path ‘/_content/BlazorDateRangePicker/daterangepicker.min.css’ for content root paths ‘xx\Client\wwwroot_content\BlazorDateRangePicker\daterangepicker.min.css’ and ‘C:\Users\xxxx.nuget\packages\blazordaterangepicker\2.0.0\build..\staticwebassets\daterangepicker.min.css’. BlazorApp.Api.Server C:\Program Files\dotnet\sdk\3.1.201\Sdks\Microsoft.NET.Sdk.Razor\build\netstandard2.0\Microsoft.NET.Sdk.Razor.StaticWebAssets.targets 191

    Any clues?

        • Daniel Roth
          Daniel Roth

          Hi Dario. For ASP.NET Core hosted apps, the reference from the server project to the client project is expected. But maybe you have a package reference to BlazorDateRangePicker in one project and then a project reference to BlazorDateRangePicker in a different project?

      • Dario Granich
        Dario Granich

        Ok, the problem was that daterangepicker.min.css existed in both www/_content/BlazorDateRangePicker/ folder and C:\Users\xxxx.nuget\packages\blazordaterangepicker\2.0.0\build..\staticwebassets folder.

        So what confuses me is when I uninstalled this package and deleted www/_content/BlazorDateRangePicker/ folder, and install it again, it will not copy files into www/_content/BlazorDateRangePicker/ ie. I cannot reference is from index.html. So if files are installed in C:\Users\xxxx.nuget\packages\blazordaterangepicker\2.0.0\build..\staticwebassets does it mean that I would have to manually copy it to _content folder and exclude it from the project in order to build the project and be able to reference it from index.html?

  • Avatar
    Javier Sánchez

    Also, for migrating existing projects, it’s required to add:

    <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>

    in index.html for using the new Authentication feature.
    If not you will receive:

    Microsoft.JSInterop.JSException: Could not find ‘AuthenticationService’ in ‘window’.

  • Avatar
    Matteo Locher

    If I want to add more scopes, for example I would like to retrieve the ’email’ from the current user. How would I need to change the configuration for the IdentityServer in the appsettings? Or how can I add custom claims? For example Firstname or Lastname?

    “IdentityServer”: {
    “Clients”: {
    “BlazorAppWithAuth1.Client”: {
    “Profile”: “IdentityServerSPA”
    }
    }
    }

  • Dario Granich
    Dario Granich

    After following all the steps I ended up with this error I cannot resolve.

    I striped my project of everything, but the error is still there…..

    An unhandled exception occurred while processing the request.
    RoutePatternException: There is an incomplete parameter in the route template. Check that each ‘{‘ character has a matching ‘}’ character.
    Microsoft.AspNetCore.Routing.Patterns.RoutePatternParser.Parse(string pattern)

    Stack Query Cookies Headers Routing
    RoutePatternException: There is an incomplete parameter in the route template. Check that each ‘{‘ character has a matching ‘}’ character.
    Microsoft.AspNetCore.Routing.Patterns.RoutePatternParser.Parse(string pattern)
    Microsoft.AspNetCore.Routing.Patterns.RoutePatternFactory.Parse(string pattern)
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory.AddEndpoints(List endpoints, HashSet routeNames, ActionDescriptor action, IReadOnlyList routes, IReadOnlyList<Action> conventions, bool createInertEndpoints)
    Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource.CreateEndpoints(IReadOnlyList actions, IReadOnlyList<Action> conventions)
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.UpdateEndpoints()
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Initialize()
    Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.get_Endpoints()
    Microsoft.AspNetCore.Routing.CompositeEndpointDataSource+<>c.b__15_0(EndpointDataSource d)
    System.Linq.Enumerable+SelectManySingleSelectorIterator<TSource, TResult>.ToArray()
    System.Linq.Enumerable.ToArray(IEnumerable source)
    Microsoft.AspNetCore.Routing.CompositeEndpointDataSource.Initialize()
    Microsoft.AspNetCore.Routing.CompositeEndpointDataSource.GetChangeToken()
    Microsoft.AspNetCore.Routing.DataSourceDependentCache.Initialize()
    System.Threading.LazyInitializer.EnsureInitializedCore(ref T target, ref bool initialized, ref object syncLock, Func valueFactory)
    System.Threading.LazyInitializer.EnsureInitialized(ref T target, ref bool initialized, ref object syncLock, Func valueFactory)
    Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher..ctor(EndpointDataSource dataSource, Lifetime lifetime, Func matcherBuilderFactory)
    Microsoft.AspNetCore.Routing.Matching.DfaMatcherFactory.CreateMatcher(EndpointDataSource dataSource)
    Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.InitializeCoreAsync()
    Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matcherTask)
    Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Builder.WebAssemblyNetDebugProxyAppBuilderExtensions+<>c+<b__5_0>d.MoveNext()
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

      • Dario Granich
        Dario Granich

        Nope, i have checked everything, i even started a new project with the latest temolate from scratch. What i noticed so far is that error appears (even in the new project) when any of the referenced projects are built with. Net standard 2.1 instead of standard 2.0? Could you confirm this issue?

      • Dario Granich
        Dario Granich

        I am unable to compile Client project.

        The problem is with App.razor and it doesnt recognize any layouts. NewLayout1 exists, and it inherits LayoutComponentBase page

        Sorry, there's nothing at this address.

        The type or namespace name ‘NewLayout1’ could not be found (are you missing a using directive or an assembly reference?)
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
        __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.Router>(0);
        __builder.AddAttribute(1, “AppAssembly”, Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Reflection.Assembly>(

        nullable restore

        line 1 “C:\Users\Source\Repos\Admin.Blazor.Client\Admin.UI\Client\App.razor”

        typeof(Program).Assembly

        line default

        line hidden

        nullable disable

        ));
        __builder.AddAttribute(2, "Found", (Microsoft.AspNetCore.Components.RenderFragment<Microsoft.AspNetCore.Components.RouteData>)((routeData) => (__builder2) => {
        __builder2.AddMarkupContent(3, "\r\n ");
        __builder2.OpenComponent<Microsoft.AspNetCore.Components.RouteView>(4);
        __builder2.AddAttribute(5, "RouteData", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.RouteData>(

        nullable restore

        line 3 “C:\Users\Source\Repos\Admin.Blazor.Client\Admin.UI\Client\App.razor”

        routeData

        line default

        line hidden

        nullable disable

        ));
        __builder2.AddAttribute(6, "DefaultLayout", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Type>(

        nullable restore

        line 3 “C:\Users\xx\Source\Repos\Admin.Blazor.Client\Admin.UI\Client\App.razor”

        typeof(NewLayout1)

        line default

        line hidden

        nullable disable

        ));
        __builder2.CloseComponent();
        __builder2.AddMarkupContent(7, "\r\n ");
        }
        ));
        __builder.AddAttribute(8, "NotFound", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
        __builder2.AddMarkupContent(9, "\r\n ");
        __builder2.OpenComponent<Microsoft.AspNetCore.Components.LayoutView>(10);
        __builder2.AddAttribute(11, "Layout", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Type>(

        nullable restore

        line 6 “C:\Users\Source\Repos\Admin.Blazor.Client\Admin.UI\Client\App.razor”

        typeof(NewLayout1)

        line default

        line hidden

        nullable disable

        ));
        __builder2.AddAttribute(12, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder3) => {
        __builder3.AddMarkupContent(13, "\r\n ");
        __builder3.AddMarkupContent(14, "

        Sorry, there\’s nothing at this address.

        \r\n “);
        }
        ));
        __builder2.CloseComponent();
        __builder2.AddMarkupContent(15, “\r\n “);
        }
        ));
        __builder.CloseComponent();
        }
        #pragma warning restore 1998

  • Avatar
    James Wil

    Is it possible to compile a dotnet project into webassembly without blazor?

    I want to use C# instead of JS, i do hosting and servicing without ASP.NET

    Currently we use C++ with emscripten, my team envision to use GO once webasm stabilizes, but i want to push C#, please tell me it is possible to produce wasm files!

    i hate both C++ and go, horrible languages

  • Avatar
    Darrell Tunnell

    Using

    <ReferenceOutputAssembly>false</ReferenceOutputAssembly>

    for the project reference to the client, breaks the authentication library sample, as the host can no longer serve up the js file “_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js” – as the package it’s in is a packagereference in the client project which the host no longer sees after this change. I am guessing you have to manually place that js file in the wwwroot on the server and update your index.html accordingly – or another alternative is to add this package reference to your server side project instead (but that seems like it would be brining in more than necessary?) – either way it would be good to have this documented?

  • Avatar
    Luis Raul Perazzolli

    I’m trying to create a new Blazor WebAssembly project with VS 2019 preview but in doing so, the dialog boxes corresponding to the project, the server project and the client project appear, and that last dialog box stays for ever. The creation process remains incomplete.

  • Avatar
    Pablo Abbate

    Hello Dan,

    I’m trying to investigate how assemblies are cached in Blazor. According to your explanation, you use blazor.boot.json to keep track of the sha-256 of every file in order to keep track of any change. With this info WebAssemblyResourceLoader will decide if it uses the cached copy or if it needs to refresh it.
    Also I realized that, when you rebuilt the project (without changing anything), all sha-256 hashes are recalculated and changed, even though the file content wasn’t changed at all. I calculated and compared both hashes manually (before and after recompile) and they are the same.

    This behaviour invalidates the entire cache and forces the application to refresh (download) all assemblies (including those who never changed).
    Is there a reason for doing this? Is there a way to only update those files that has been changed? Maybe I’m missing something here.

    Thansk in advance!

    Pablo

    • Daniel Roth
      Daniel Roth

      Hi Pablo. You are correct that blazor.boot.json is used to record the hashes of the various built files. If the files haven’t changed, then the hashes should remain the same. I’m not seeing the behavior you describe with our latest release 3.2 Preview 3. When I create a new Blazor WebAssembly project and rebuild the hashes in the generated blazor.boot.json remain the same. If you’re able to reproduce this reliably with 3.2 Preview 3, could you please open a GitHub issue with detailed steps to reproduce the problem so that we can investigate? https://github.com/dotnet/aspnetcore/issues.

      • Avatar
        Pablo Abbate

        Hi Dan,
        I’m sorry. I ommited important info: I’m working on Release (not Debug) mode.

        Steps:
        a) Create new Blazor Assembly App (not ASP.NET Core hosted)
        b) Build it using RELEASE mode.
        c) Check file \bin\Release\netstandard2.1\wwwroot_framework\blazor.boot.json. For example: hash for assembly “Microsoft.AspNetCore.Blazor.HttpClient.dll” is (in my case) “sha256-rG0but8jR1vtYFE5orZy51QUgLfssOF1zj+GBQWaCE8=
        d) Recompile the project
        e) Now, the same assembly has a new hash: “sha256-qGCGcP51kxvi3yGHDnmKeMiQscwABPurn9CPyzz7jqA=

        I’m using Blazor 3.2.0-preview3 version. SDK: 3.1.300-preview-015048 – VS 16.6.0 Preview 2.1
        Is this a normal behaviour? Do you get the same result from your side?
        Thanks again!