自动读取导航菜单中 Razor 页面的路径

automatically read path to Razor page in Nav Menu

我想要做的是读取每个 Razor 页面的 @page 属性指示的路径,在导航菜单中 link 到它。无论出于何种原因我想更改 url.

时都不必手动重做 href

但是我没有找到从组件读取页面属性的方法,是我遗漏了什么还是有其他方法可以做到这一点?

只是为了形象化我想要的东西,这就是它最终应该大致的样子:

<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>

Blazor 框架不会公开任何 public API* 来执行您想要的操作。您或许可以 post 在 github 上作为功能请求。

*在内部,路径 table 是通过扫描您的组件以查找 RouteAttribute 生成的。

话虽如此,还有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).

感谢 Jesse Good 的输入,我使用反射找到了以下相对简单的问题答案。

导航菜单:

        <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>

解析函数:

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;
}