Prevent Blazor Router to found some components with @page directive

48 Views Asked by At

In blazor Server-Side, I have a Razor Class Library with several components that can be routed because they have the @page directive.

This is my code on App.razor:

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly"
            AdditionalAssemblies="typeof(MyRazorLibrary.SomeClass).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

On that example, I add as additional assembly the Razor class library, so the blazor app adds to routing all the Page components on that assembly. It works.

However, I want to prevent that every page of the assembly can be routed, because it's a RCL which can be used by different Blazor Apps and I want to select on each app the exactly pages that I want for it.

Is it possible?

I expect something like add on a list the specific types of the pages that I want to use from the RCL. Something like this:

Blazor App Nº1

  • Page A on RCL --> Included on Router.
  • Page B on RCL --> Included on Router.
  • Page C on RCL --> Not included.

Blazor App Nº2

  • Page A on RCL --> Not included.
  • Page B on RCL --> Included on Router.
  • Page C on RCL --> Not included.
1

There are 1 best solutions below

0
On

The simplest way I know is to remove all the routes from the RCL. The pages are still there as components.

So Home would be :


<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@code{
    [Parameter] public int ID {get;set;}
}

You can then add the routes to a separate specific RCL for each project, or directly into the project:

HomePage.razor

@page "/"
@page "/item/{ID:int}"

<Home ID="this.ID" />

@code {
    [Parameter] public int ID { get; set; }
}

Note that you do need to pass any route parameters through.

I actually use this approach for my applications. All the functionality is in a Form component. The route then just sets up the form to use.