I created a .NET 9 Blazor web app project with VS 2022 17.12.0, and included personal accounts for the auth.
I want to set up an admin section, that only authenticated users can access it. To test this out, I added a \Pages\Admin
folder to the client project, and added an _Imports.razor
file with the following single line of code:
@layout AdminLayout
I then added an AdminLayout.razor
file that contained the following (really simple for testing, the final layout will contain more):
@inherits LayoutComponentBase
<h1>Admin</h1>
@Body
Finally, I added a Home.razor
file that contains this code:
@page "/admin"
<PageTitle>Admin</PageTitle>
<h1>Admin home</h1>
I didn't touch the server project at all. My client project looks like this:
I ran the project, and tried to navigate to /admin
, but the icon on the browser's title bar shows a whirling icon, like when a page is loading, but it doesn't load the page. The machine's CPU and RAM increase steadily until something crashes.
I don't see any errors anywhere, and all other pages work fine.
However, if I remove the @layout
line from _Imports.razor
and put it at the top of Home.razor
then it all works fine.
Anyone able to explain what I'm doing wrong? The identity pages that came with the template use @layout
in the _Imports.razor
files, and that works fine. I would like to be able to do the same, rather than have to specify the layout in every page.
By adding a @layout
statement to _Imports.razor
, you have said that every Blazor component in that folder should use AdminLayout
for its layout.
When you navigate to \admin
, it tries to create an instance of the Home
component. As that's in the Admin
folder, it knows that Home
should use AdminLayout
for its layout, and so tries to create an instance of AdminLayout
.
However, AdminLayout
is also in that folder, so is specified as using AdminLayout
(ie itself) for its layout. This means that in order to create an instance of AdminLayout
it needs to create an instance of AdminLayout
, which in turn means, well I guess you see what's going on here!
This explains the high CPU and increasing RAM.
If you look at the folder structure that the templates uses for the identity stuff, you'll see that the layout components are in a different folder, which is why they work. If you move your AdminLayout
to another folder, it should work fine.