Search code examples
c#blazorblazor-server-sidevisual-studio-2022maui-blazor

Page NOT in the shared project does not show correctly in browser


I am trying to create a project in .net 9 and Blazor using the ".net Maui Blazor and Web App" template in Visual Studio.

I have created the project, and run it successfully, and I can see the project run as a Windows App, or set the Start Up project to the web project, and then run it in a browser.

So all good so far.

Now I add a test page to the Web Project called "Test". I put it in the Web Project because I do NOT want it to be shared with the Maui project. I then run the project again, and type in the address of the test page. The "Test" page is displayed correctly for 1 second, and then disappears with a "not found" message.

If I add a test page to the Shared Directory, it displays normally.

I have been unable to resolve this. I have created a Test Repo here: https://github.com/gregoryagu/MauiApp5

What do I need to do to get the Test page to display normally?


Solution

  • First, why it doesn't work. The chain here is:

    • In Web/Program.cs the root is app.MapRazorComponents<App>()

    • Web/Components.App.razor uses <Routes @rendermode="InteractiveServer" />

    • Shared/Routes.razor has <Router AppAssembly="typeof(Layout.MainLayout).Assembly" >

    So the router scans for pages in the assembly that contains MainLayout. What you would need (but doesn't immediately work) is

    <Router AppAssembly="typeof(Layout.MainLayout).Assembly" 
          AdditionalAssemblies="typeof(Pages.Test)">    
    

    Since you can't have a circular dependency from Shared back to the Web assembly you will need a separate Router. I'm not sure if there are any disadvantages to this, but be ware.

    • copy Routes.razor to Web/Components. Rename it to RoutesWeb.razor .
    • Add AdditionalAssemblies="[typeof(Pages.Test).Assembly]" to the first line.
    • Also add Shared to DefaultLayout="typeof(Shared.Layout.MainLayout)"
    • In App.razor , change the Routes element to <RoutesWeb @rendermode="InteractiveServer" />