'automatically read path to Razor page in Nav Menu

What I want to do is to read the path as indicated with the @page attribute of every Razor Page, to link to it in the Nav Menu. With the purpose of not having to manually redo a href when for whatever reason I want to change the url.

I did however not find a way to read the page attribute from components, am I missing something or is there another way of doing this?

Just to visualise what I want, this is how it should roughly look in the end:

<div class="nav-item px-3">
    <NavLink class="nav-link" href=UploadPage.page>
        <span class="oi oi-data-transfer-upload" aria-hidden="true"></span> Content Upload
    </NavLink>
</div>


Solution 1:[1]

Thanks to the input by Jesse Good I found the following relatively simple answer to my problem, using reflection.

The Navmenu:

        <div class="nav-item px-3">
            <NavLink class="nav-link" href="@(PathTo<MyRazorPage>())">
                <span class="oi oi-book" aria-hidden="true"></span> My ePaper
            </NavLink>
        </div>

The resolving Function:

private string PathTo<T>()
{
    var attributes = typeof(T).GetCustomAttributes(typeof(Microsoft.AspNetCore.Components.RouteAttribute), inherit: false);
    var route = (Microsoft.AspNetCore.Components.RouteAttribute) attributes[0]; 
    return route.Template;
}

Solution 2:[2]

The blazor framework doesn't expose any public APIs* to do what you want. You could perhaps post on github as a feature request.

*Internally, a route table is generated by scanning your assembilies for RouteAttribute.

Having said that, there is this blog post about using source generators to read the RouteAttribute of each component and generate the nav menu for you. Unfortunately, in order to use it, you have to turn off razor source generation to do it currently as source generators cannot see the output of other source generators. Hopefully in the future, we will be able to use source generators with the razor compiler (Here is the issue tracking it).

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 Christian O.
Solution 2 Jesse Good