'Blazor WebAssembly InvalidCastException when running Published version on IIS

I have a Blazor WebAssembly application that works fine when debugging, but throws an exception when running on IIS (Published):

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Specified cast is not valid.
System.InvalidCastException: Specified cast is not valid.
   at Microsoft.AspNetCore.Components.Reflection.MemberAssignment.GetPropertiesIncludingInherited(Type , BindingFlags )+MoveNext()
   at Microsoft.AspNetCore.Components.ComponentFactory.CreateInitializer(Type )
   at Microsoft.AspNetCore.Components.ComponentFactory.PerformPropertyInjection(IServiceProvider , IComponent )
   at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider , Type )
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateComponent(Type )
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateChildComponentOnFrame(RenderTreeFrame& , Int32 )
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(DiffContext& , Int32 )
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewSubtree(DiffContext& , Int32 )
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InsertNewFrame(DiffContext& , Int32 )
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange(DiffContext& , Int32 , Int32 , Int32 , Int32 )
   at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff(Renderer , RenderBatchBuilder , Int32 , ArrayRange`1 , ArrayRange`1 )
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder , RenderFragment , Exception& )
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch(RenderQueueEntry )
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue()

This error is quite useless i.m.o, as I can not find the exact cause, rather than it being an invalid cast exception.

Because debugging is not possible on published IIS site, I added Console.WriteLine to the Program.cs and the first Index.razor. However, the error occurs before the Index.razor is being rendered. And all code in my Program.main before the await builder.Build().RunAsync(); call works fine as well.

So I suppose it has something to do with my App.razoror MainLayout.razor. Now the MainLayout.razor is located inside a Razor Class Library with namespace Libs.Blazor.Components.Shared.

Program.cs

  /// <summary>
  /// Program entry
  /// </summary>
  public class Program {

    /// <summary>
    /// Entry point of application
    /// </summary>
    /// <param name="args">Arguments to pass</param>
    /// <returns>Task with a result</returns>
    public static async Task Main (String[] args) {
      var builder = WebAssemblyHostBuilder.CreateDefault(args);
      builder.RootComponents.Add<App>("#app");
      builder.RootComponents.Add<HeadOutlet>("head::after");

      HttpClient http = new HttpClient() {
        BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
      };

      IHostEnvironment hostEnvironment = new HostEnvironment() {
        ApplicationName = builder.HostEnvironment.Environment,
        EnvironmentName = builder.HostEnvironment.Environment,
        ContentRootPath = builder.HostEnvironment.Environment
      };

      builder.Services.AddScoped(sp => http);
      builder.Services.AddScoped(sp => hostEnvironment);

      using HttpResponseMessage response = await http.GetAsync("appsettings.json"); //Load the appsettings
      using Stream stream = await response.Content.ReadAsStreamAsync();

      builder.Configuration.AddJsonStream(stream);
      await builder.Build().RunAsync();
    } // Main

    /// <summary>
    /// HotEnvironment filled by WebAssembly
    /// </summary>
    internal class HostEnvironment :IHostEnvironment {
      private String m_EnvironmentName;
      private String m_ApplicationName;
      private String m_ContentRootPath;
      private IFileProvider m_ContentRootFileProvider;

      /// <summary>
      /// EnvironmentName
      /// </summary>
      public String EnvironmentName { [DebuggerStepThrough()] get { return m_EnvironmentName; } set { m_EnvironmentName = value; } }

      /// <summary>
      /// ApplicationName
      /// </summary>
      public String ApplicationName { [DebuggerStepThrough()] get { return m_ApplicationName; } set { m_ApplicationName = value; } }

      /// <summary>
      /// ContentRootPath
      /// </summary>
      public String ContentRootPath { [DebuggerStepThrough()] get { return m_ContentRootPath; } set { m_ContentRootPath = value; } }

      /// <summary>
      /// FileProvider
      /// </summary>
      public IFileProvider ContentRootFileProvider { [DebuggerStepThrough()] get { return m_ContentRootFileProvider; } set { m_ContentRootFileProvider = value; } }
    } // Class HostEnvironment
  } // Class Program

App.razor

<Router AppAssembly="@typeof(Program).Assembly" AdditionalAssemblies="new[] { typeof(Libs.Blazor.Components.Shared.MainLayout).Assembly }">
  <Found Context="routeData">
    <RouteView RouteData="@routeData" DefaultLayout="@typeof(Libs.Blazor.Components.Shared.MainLayout)" />
  </Found>
  <NotFound>
    <LayoutView Layout="@typeof(Libs.Blazor.Components.Shared.MainLayout)">
      <p>Sorry, there's nothing at this address.</p>
    </LayoutView>
  </NotFound>
</Router>

Libs.Blazor.Components.Shared.MainLayout

@namespace Libs.Blazor.Components.Shared
@inherits LayoutComponentBase

<body id="LibsBody" class="LibsBody" style="cursor:default;">
  @Body
  <div id="LibsHidden"></div>
</body>

So I am quite confused why I get this Invalid Cast Exception running the application on IIS, but not when I debug it in VS.



Solution 1:[1]

By accident I solved this issue by having a look at the Publish Profiles. Somehow the target runtime was set to Portable, instead of the required browser-wasm.

Target Runtime needs to be set to browser-wasm

Solution 2:[2]

I had this same problem. The steps that worked for me to resolve were installing the .net 6 hosting bundle on the Windows Server hosting IIS. I then rebooted the IIS server and republished my application from VS2022. Now everything is working. Hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dagovax
Solution 2 Links19