Blazor WebAssembly 3.2.0 Preview 3 release now available

Daniel Roth

Daniel

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

  • Debugging in Visual Studio and Visual Studio Code
  • Auto-rebuild in Visual Studio
  • Configuration
  • New HttpClient extension methods for JSON handling

Get started

To get started with Blazor WebAssembly 3.2.0 Preview 3 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-preview3.20168.3

If you’re on Windows using Visual Studio, we recommend installing the latest preview of Visual Studio 2019 16.6. Installing Visual Studio 2019 16.6 Preview 2 or later will also install an updated version of the .NET Core 3.1 SDK that includes the Blazor WebAssembly template, so you don’t need to separately install it.

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

  • Update all Microsoft.AspNetCore.Components.WebAssembly.* package references to version 3.2.0-preview3.20168.3.
  • Update all Microsoft.AspNetCore.Blazor.* package references to version 3.2.0-preview3.20168.3.

You’re all set – easy peasy!

Debugging

You can now debug Blazor WebAssembly apps directly from Visual Studio and Visual Studio Code. You can set breakpoints, inspect locals, and step through your code. You can also simultaneously debug your Blazor WebAssembly app and any .NET code running on the server. Using the browser dev tools to debug your Blazor WebAssembly apps is also still supported.

Enable debugging

To enable debugging in an existing Blazor WebAssembly app, update launchSettings.json in the startup project of your app to include the following inspectUri property in each launch profile:

"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}"

This property enables the IDE to detect that this is a Blazor WebAssembly app and instructs the script debugging infrastructure to connect to the browser through Blazor’s debugging proxy.

Once updated, your launchSettings.json file should look something like this:

{
    "iisSettings": {
      "windowsAuthentication": false,
      "anonymousAuthentication": true,
      "iisExpress": {
        "applicationUrl": "http://localhost:50454",
        "sslPort": 44399
      }
    },
    "profiles": {
      "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Development"
        }
      },
      "BlazorApp1.Server": {
        "commandName": "Project",
        "launchBrowser": true,
        "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
        "applicationUrl": "https://localhost:5001;http://localhost:5000",
        "environmentVariables": {
          "ASPNETCORE_ENVIRONMENT": "Development"
        }
      }
    }
  }

Visual Studio

To debug a Blazor WebAssembly app in Visual Studio:

  1. Ensure you have installed the latest preview release of Visual Studio 2019 16.6 or later.
  2. Create a new ASP.NET Core hosted Blazor WebAssembly app.
  3. Hit F5 to run the app in the debugger.
  4. Set a breakpoint in Counter.razor in the IncrementCount method.
  5. Browser to the Counter tab and click the button to hit the breakpoint:

    Debug Counter

  6. Check out the value of the currentCount field in the locals window:

    View locals

  7. Hit F5 to continue execution.

While debugging your Blazor WebAssembly app you can also debug your server code:

  1. Set a breakpoint in the FetchData.razor page in OnInitializedAsync.
  2. Set a breakpoint in the WeatherForecastController in the Get action method.
  3. Browser to the Fetch Data tab to hit the first breakpoint in the FetchData component just before it issues an HTTP request to the server:

    Debug Fetch Data

  4. Hit F5 to continue execution and then hit the breakpoint on the server in the WeatherForecastController:

    Debug server

  5. Hit F5 again to let execution continue and see the weather forecast table rendered.

Visual Studio Code

To debug a Blazor WebAssembly app in Visual Studio Code:

  1. Install the C# extension and the JavaScript Debugger (Nightly) extension with the debug.javascript.usePreview setting set to true.

    Extensions

    JS preview debugger

  2. Open an existing Blazor WebAssembly app with debugging enabled.

    a. If you get the following notification that additional setup is required to enable debugging, recheck that you have the correct extensions installed and JavaScript preview debugging enabled and then reload the window:

    Additional setup requried

    b. A notification should offer to add required assets for building and debugging to the app. Select “Yes”.

    Add required assets

  3. Starting the app in the debugger is then a two-step process:

    a. Start the app first using the “.NET Core Launch (Blazor Standalone)” launch configuration.

    b. Then start the browser using the “.NET Core Debug Blazor Web Assembly in Chrome” launch configuration (requires Chrome). To use the latest stable release of Edge instead of Chrome, change the type of the launch configuration in .vscode/launch.json from pwa-chrome to pwa-msedge.

  4. Set a breakpoint in the IncrementCount method in the Counter component and then select the button to hit the breakpoint:

    Debug Counter in VS Code

Known limitations

There are a number of limitations with the current debugging experience in Visual Studio and Visual Studio Code. The following debugging features are not yet fully implemented:

  • Inspecting arrays
  • Hovering to inspect members
  • Step debugging into or out of managed code
  • Full support for inspecting value types
  • Breaking on unhandled exceptions
  • Hitting breakpoints during app startup
  • Debugging an app with a service worker

We expect to continue to improve the debugging experience in future releases. We appreciate your feedback to help us get the Blazor WebAssembly debugging experience right!

Auto-rebuild in Visual Studio

Visual Studio 2019 16.6 will watch for file changes in .cs and .razor files across the solution and automatically rebuild and restart the app so that the changes can be seen by simply refreshing the browser. This enables auto-rebuild support for ASP.NET Core hosted Blazor WebAssembly projects and Razor Class Libraries. Instead of manually rebuilding and restarting the app when making code changes, just edit, save, and then refresh the browser.

To use auto-rebuild, run the app using IIS Express and without the debugger attached (Ctrl-F5 instead of F5).

Auto-rebuild is not yet enabled for standalone Blazor WebAssembly projects. With standalone Blazor WebAssembly apps, you can instead edit files, rebuild the app, and then refresh the browser without restarting the web server.

Configuration

Blazor WebAssembly apps now have built-in support for loading configuration data from appsettings.json and environment specific configuration data from appsettings.{environment}.json.

To add configuration data to your Blazor WebAssembly app:

  1. Add an appsettings.json file in the wwwroot folder of your Blazor WebAssembly app:
{
    "message": "Hello from config!"
}
  1. Inject an IConfiguration instance into your components to access the configuration data.
@page "/"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Configuration example</h1>

<p>@Configuration["message"]</p>
  1. Run the app to see the configured message displayed on the home page.
  2. To optionally override this configuration with values specific to the Development environment, add an appsettings.Development.json to your wwwroot folder:
{
    "message": "Hello from Development config!"
}
  1. If you now run the app in Development, you’ll see the new message.

Note: Blazor WebAssembly apps load the configuration data by downloading the JSON files to the browser, so these configuration files must be publicly addressable. Do not store secrets in these configuration files, as they are public and can be viewed by anyone.

New HttpClient extension methods for JSON handling

The .NET team has been hard at work creating a full set of new extension methods for HttpClient that handle JSON serialization and deserialization using System.Text.Json. These extension methods are now available in preview with the System.Net.Http.Json package and they will replace the existing helper methods in the Microsoft.AspNetCore.Blazor.HttpClient package. We haven’t updated the Blazor WebAssembly template yet to use the new extension methods, but we will in our next Blazor WebAssembly preview update.

You can try the new extension methods yourself by replacing the Microsoft.AspNetCore.Blazor.HttpClient package with the newer System.Net.Http.Json package. Then add @using System.Net.Http.Json to your _Imports.razor file and update your code as follows:

Microsoft.AspNetCore.Blazor.HttpClient System.Net.Http.Json
GetJsonAsync GetFromJsonAsync
PostJsonAsync PostAsJsonAsync
PutJsonAsync PutAsJsonAsync

The updated implementation of the FetchData component in the default Blazor WebAssembly template looks like this:

@code {
    private WeatherForecast[] forecasts;

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

System.Net.Http.Json also provides a JsonContent class that can be used for sending serialized JSON, as well as convenient helper methods for reading JSON from an HttpContent instance.

Look for more details on System.Net.Http.Json to be published soon on the .NET blog.

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, update to version 3.1.201 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
    

    To address this issue, update to your package reference to Microsoft.AspNetCore.Components to 3.1.3 or newer. If your project reference the Microsoft.AspNetCore.Components package through a transitive package reference that has not been updated, you can add a reference in your project to resolve the issue in your project.

  • 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!

146 comments

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

  • Avatar
    Alex Whittle

    As recent releases are related to WebAssembly projects what is happening with Blazor Server Side? We’ve absolutely no interest in WebAssembly projects at the moment, should we be keeping up to date with these releases anyway? Assume auto-rebuild applies to SSB projects also?

    • Daniel Roth
      Daniel RothMicrosoft employee

      Hi Alex. Blazor Server shipped with .NET Core 3.1 LTS and auto-rebuild already works for Blazor Server apps with Visual Studio 16.4 or later. The next update for Blazor Server will come with .NET 5 later this year. If you’re building with Blazor Server and you have no plans to use Blazor WebAssembly then there’s no need keep up with the Blazor WebAssembly updates. The Blazor WebAssembly updates don’t impact Blazor Server apps at all. Blazor WebAssembly is being built on the same component model that shipped in .NET Core 3.1 with Blazor Server, so the same components work with either hosting model.

  • Stephen Brown
    Stephen Brown

    Hi,

    This is great stuff. I have an issue running my project though, debugging won’t connect to the proxy, seems to be a timeout issue:

    System.TimeoutException: Failed to start the debug proxy within the timeout period of 10 seconds.
    at Microsoft.AspNetCore.Builder.DebugProxyLauncher.LaunchAndGetUrl(IServiceProvider serviceProvider)
    at Microsoft.AspNetCore.Builder.WebAssemblyNetDebugProxyAppBuilderExtensions.<>c.<b__0_1>d.MoveNext()
    — End of stack trace from previous location where exception was thrown —
    at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 14.6847ms 500 text/plain
    Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/1.1 GET https://localhost:5001/_framework/debug/ws-proxy?browser=ws%3A%2F%2Flocalhost%3A51590%2Fdevtools%2Fbrowser%2F5990c061-f462-4f4e-ad68-4ce8606208ea
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.

    Any ideas?

    Thanks

    • Avatar
      Matthew Hill

      I have the same issue after upgrading my project. I noticed that in IIS Express it shows myApp.Server whereas in a new project it shows BlazorApp.Client. I changed the debugger browser to Microsoft Edge and found it loaded the site (still as myApp.Server) but debugging doesn’t appear to work. Maybe I missed something in the update instructions. If you managed to get this to work I’d appreciate the help.

        • Avatar
          Matthew Hill

          Hi Daniel, definitely works with a new project using Chrome or Edge. Shows as BlazorApp5.Client in IIS express and mine is always myApp.Server. Leads me to believe the Server > Client linking isn’t working quite right.

          I’ll have one more round of disabling things and comparing with a new project. Failing that I’ll have to rebuild from a new project.

          Thanks

  • Avatar
    Evan Weeks

    When I break on the line:

    NavManager.NavigateTo(url);

    in one of my components, after hitting F5 to continue, the debugger detaches but the IISExpress instance continues to run.

  • Avatar
    Darren Ford

    I found another issue related to the debugging via Visual Studio. For an application I am writing, it is using cookie authentication. The cookies are set by another primary application. Those cookies are domain specific. To be able to debug locally and use the external system for auth to set the cookies, I edited my ‘hosts’ file to map the address localhost.myrealdomainthatauths.com to localhost/127.0.0.1. This means that the applicationhost.config file has to be tweaked a bit to look like this:

    <bindings>
              <binding protocol="http" bindingInformation="*:53340:localhost.localdebugging.com" />
              <binding protocol="https" bindingInformation="*:44390:localhost.localdebugging.com" />
    </bindings>

    and my launchSettings.json looks like this:

    {
        "useWebAssemblyDebugging": true,
        "iisSettings": {
          "windowsAuthentication": false,
          "anonymousAuthentication": true,
          "iisExpress": {
            "applicationUrl": "http://localhost.localdebugging.com:53340",
            "sslPort": 44390
          }
        },
        "profiles": {
          "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          },
          "BlazorDebugApp.Server": {
            "commandName": "Project",
            "launchBrowser": true,
            "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
            "applicationUrl": "https://localhost:5001;http://localhost:5000",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          }
        }
      }

    When using a sample app created directly from the template, debugging works. When I make these tweaks to have the sample app use a fully qualified domain mapped DNS-wise locally via hosts file, the app will run, but the debugger doesn’t load symbols and stop at breakpoints. Since my real app didn’t work and in fact crashes the debugger or fails to load symbols, I tried to isolate the issue by just testing the dns thing first using a sample app created directly from the new template.

    So here’s the order of my steps I took:

    Update visual studio to latest preview per instructions
    Update my real app to the new preview 3 lib versions per instructions
    Alter my launchsettings to contain the ‘inspectUri’ additions.
    Set breakpoint and fire up the application in the debugger.
    Chrome opens with app
    Debugger promptly crashes
    Create sample app directly from latest template
    Review the sample app launchSettings to see if it has the ‘inspectUri’ changes and it does.
    Fire up the sample app and set breakpoint which actually works….yay but puzzled why mine won’t work.
    Compare sample app launch settings to mine and discover there is an entry NOT mentioned in this post which is:

    "useWebAssemblyDebugging": true,

    Get excited because “that must be the issue” so add that to my launchSettings in my real app.
    Fire up my real app, same result, doesn’t work, debugger crashes.
    Try it again just for the heck of it, this time Visual Studio locks up so I manually kill it.
    Go into panic mode checking csproj files and making sure the versions I have match up…and they do.
    Now start isolating potential culprits starting with the hosts file and dns fiddling by only changing this one thing for the sample app.
    Now the sample app doesn’t work with just the applicationhost.config and launchSettings change from localhost to localhost.localdebugging.com so at a minimum this does indeed break it. Also, I must note that for some reason Visual Studio can not attach to the debugger using the fully qualified domain entry without running as Administrator(separate issue but annoying and I don’t know why admin is needed to run this way).

    So to reproduce this issue do the following:

    Create sample app using latest template(and host with .net core..don’t forget)
    Start the app and add breakpoint to make sure it works before next step.
    Edit your local ‘hosts’ file and add

    127.0.0.1 localhost.localdebugging.com

    Modify your applicationhost.config file so it looks like this (using the port numbers it already had set up for your sample app)

    <bindings>
              <binding protocol="http" bindingInformation="*:[your port number]:localhost.localdebugging.com" />
              <binding protocol="https" bindingInformation="*:[your other number]:localhost.localdebugging.com" />
    </bindings>

    Modify your launchSettings.json file and change the url to the fully qualified on you used in the hosts file

    "applicationUrl": "http://localhost.localdebugging.com:[your port number]",

    Now fire up the app and Chrome should open to the ssl version of the url.
    Should get error trying to attach to debugger…GRRR, now re-open Visual Studio as Administrator and fire up the debugger again.
    App should come up and work but debugger doesn’t load symbols and breakpoint doesn’t work.

    I also noticed a new file beside the applicationhost.config with the name debuggerConfiguration-[GUID].json which contains the non ssl port for the Chrome debugger.

    {"chromiumDebuggerPort":53350}

    All in all it doesn’t work quite yet for me and have seen several different behaviors occur when trying including:

    Debugger crashed killing the server side process leaving Chrome open
    Debugger staying alive along with Chrome and app fully functional, just no breakpoints loaded and working
    Debugger crashing and stopping immediately followed by Visual Studio hanging and ‘Not responding’

  • Avatar
    Rui Hou

    Hi! Thanks for all the work at improving Blazor WebAssembly!
    I wanted to try out my project with preview 3 on Azure App Service but it failed to build due to a linker error. It works well locally. Is that because of the SDK version on Azure? How may I change the SDK version to use for deployment? Or is it more likely that the .dll got removed during publish? I have added

    <BlazorWebAssemblyEnableLinking>true</BlazorWebAssemblyEnableLinking>

    in the client project.
    Thanks for bearing with me as I’m new to this…

    Command: oryx build /home/site/repository -o /home/site/wwwroot –platform dotnet –platform-version 3.1 -i /tmp/8d7d27f26d3daf0 –log-file /tmp/build-debug.log
    Build orchestrated by Microsoft Oryx, https://github.com/Microsoft/Oryx
    You can report issues at https://github.com/Microsoft/Oryx/issues

    Oryx Version : 0.2.20200114.13, Commit: 204922f30f8e8d41f5241b8c218425ef89106d1d, ReleaseTagName: 20200114.13
    Build Operation ID: |XqcchouI2n4=.1be129a3_
    Repository Commit : 4fe2e31c9019c4139986e25d850f58e42ea5d1e9

    Source directory : /tmp/8d7d27f26d3daf0
    Destination directory : /home/site/wwwroot

    Using .NET Core SDK Version: 3.1.100

    Restoring packages…
    Restore completed in 27.11 sec for /home/site/repository/Client/VisualGo.Client.csproj.
    Restore completed in 608.88 ms for /home/site/repository/Server/VisualGo.Server.csproj.
    Restore completed in 61.35 ms for /home/site/repository/Shared/VisualGo.Shared.csproj.
    Publishing output to ‘/home/site/wwwroot’
    Microsoft (R) Build Engine version 16.4.0+e901037fe for .NET Core
    Copyright (C) Microsoft Corporation. All rights reserved.

    Restore completed in 326.06 ms for /home/site/repository/Client/VisualGo.Client.csproj.
    Restore completed in 150.06 ms for /home/site/repository/Server/VisualGo.Server.csproj.
    Restore completed in 138.49 ms for /home/site/repository/Shared/VisualGo.Shared.csproj.
    VisualGo.Shared -> /home/site/repository/Shared/bin/Release/netstandard2.1/VisualGo.Shared.dll
    Fatal error in Mono IL Linker
    /var/nuget/microsoft.aspnetcore.components.webassembly.build/3.2.0-preview3.20168.3/targets/Blazor.MonoRuntime.targets(247,5): error : Unhandled exception. Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: ‘obj/Release/netstandard2.1/VisualGo.Client.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null’ [/home/site/repository/Client/VisualGo.Client.csproj]
    —> Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: ‘obj/Release/netstandard2.1/VisualGo.Client.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null’
    at Mono.Cecil.BaseAssemblyResolver.Resolve(AssemblyNameReference name, ReaderParameters parameters)

    at Mono.Linker.Driver.Main(String[] args)
    /var/nuget/microsoft.aspnetcore.components.webassembly.build/3.2.0-preview3.20168.3/targets/Blazor.MonoRuntime.targets(247,5): error : ILLink failed with exit code 134. [/home/site/repository/Client/VisualGo.Client.csproj]

  • Avatar
    Orides Pavaneli

    Hi Daniel, i try to test the CallWebApi official sample, it’s not working for me.

    Sample: AspNetCore.Docs-master\aspnetcore\blazor\common\samples\3.x\BlazorWebAssemblySample
    System.Net.Http.Json (3.2.0-preview3.20175.8) package used to replace Microsoft.AspNetCore.Blazor.HttpClient package.
    The required WebApi is up and running, all intructions applied.

    Option: Call a Web Api (https://localhost:44365/CallWebApi)
    When clicked, shows the alert “An unhandled erros has ocorred. Reload”. The page is prepared for sending the request.
    If you dismiss the alert and click on the button “Request”, i got the following response:

    Response
    Status:
    RedirectMethod

    Using Google Chrome (version 80.0.3987.149 (Oficial Version) 64 bits)

    Body:
    TypeError: Failed to fetch
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.doFetch (System.Threading.Tasks.TaskCompletionSource1[TResult] tcs, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2d7e5c0 + 0x00988> in <filename unknown>:0
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2d565d8 + 0x00184> in <filename unknown>:0
    at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task
    1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) in :0
    at BlazorSample.Components.HTTPRequestTester.DoRequest () [0x001db] in E:\Desenvolvimento\repos\Samples\BlazorWasm\BlazorWebAssemblySample\Components\HTTPRequestTester.razor:109

    Using Firefox (version 74.0 64bits)

    Body:
    TypeError: NetworkError when attempting to fetch resource.
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.doFetch (System.Threading.Tasks.TaskCompletionSource1[TResult] tcs, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2cc78b0 + 0x00988> in <filename unknown>:0
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ca1110 + 0x00184> in <filename unknown>:0
    at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task
    1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) in :0
    at BlazorSample.Components.HTTPRequestTester.DoRequest () in :0

    Using Microsoft Edge (version 44.18362.449.0)

    Body:
    TypeError: Falha ao buscar
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.doFetch (System.Threading.Tasks.TaskCompletionSource1[TResult] tcs, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2cc78b0 + 0x00988> in <filename unknown>:0
    at WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) <0x2ca1110 + 0x00184> in <filename unknown>:0
    at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task
    1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) in :0
    at BlazorSample.Components.HTTPRequestTester.DoRequest () in :0

    Using any browser:

    Headers:
    empty…

  • Avatar
    Daniel Smith

    I’m on 16.6 Preview 2 and auto rebuild doesn’t seem to be working for me, even with a fresh new project. Is there some other setting that needs to be enabled to make this work?

  • Avatar
    Emil Emilsson

    Im doing something like this

        [Inject]
        protected System.Net.Http.HttpClient Http { get; set; }
    
            List<TolfraediDTO> tolfraediKyn =
                await System.Net.Http.Json.HttpClientJsonExtensions
                .GetFromJsonAsync<List<TolfraediDTO>>(
                    Http, "/api/tolfraedi/GetAsync");
    

    after changing from the httpclient (which was working in the earlier version)

    I allways get this error when calling this.

    NotSupportedException: The provided ContentType is not supported; the supported types are ‘application/json’ and the structured syntax suffix ‘application/+json’.
    System.Net.Http.Json.HttpContentJsonExtensions.ValidateContent(HttpContent content)

    I added this to startup.cs

            // Server Side Blazor doesn't register HttpClient by default
            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                // Setup HttpClient for server side in a client side compatible fashion
                services.AddScoped<HttpClient>(s =>
                {
                    // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
                    var uriHelper = s.GetRequiredService<NavigationManager>();
                    HttpClient ret = new HttpClient
                    {
                        BaseAddress = new Uri(uriHelper.BaseUri)
                    };
                    return ret;
                });
            }
    

    any ideas ?

    Regards,
    Emil