在Blazor组件中获取当前Url

Car*_* L. 10 c# asp.net-core blazor

我需要知道当前页面的url,以检查是否必须将某种样式应用于元素.下面的代码就是一个例子.

@using Microsoft.AspNetCore.Blazor.Services
@inject IUriHelper UriHelper
@implements IDisposable

<h1>@url</h1>
<nav>
    <div class="nav-wrapper">
        <a href="#" class="brand-logo">Blazor</a>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
            <li>
                <NavLink href="/" Match=NavLinkMatch.All>
                    Home
                </NavLink>
            </li>
            <li>
                <NavLink href="/counter">
                    Counter
                </NavLink>
            </li>
            <li>
                <NavLink href="/fetchdata">
                    Fetch data
                </NavLink>
            </li>
        </ul>
    </div>
</nav>

@functions {

    private string url = string.Empty;

    protected override void OnInit()
    {
        url = UriHelper.GetAbsoluteUri();
        UriHelper.OnLocationChanged += OnLocationChanged;
    }

    private void OnLocationChanged(object sender, LocationChangedEventArgs e)
    {
        url = newUriAbsolute;
    }

    public void Dispose()
    {
        UriHelper.OnLocationChanged -= OnLocationChanged;
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了与Blazor存储库中的NavLink组件相同的方法,但它没有用.有任何想法吗?.

dan*_*era 20

简而言之,使用来自IUriHelper的GetAbsoluteUri():

1)不要忘记在注射时设置UriHelper Uri:

@inject NavigationManager MyNavigationManager
Run Code Online (Sandbox Code Playgroud)

或者在基类继承中获得"代码隐藏"体验NavigationManager:

using Microsoft.AspNetCore.Components;
...
[Inject] 
public NavigationManager MyNavigationManager {get; set;}
Run Code Online (Sandbox Code Playgroud)

2)调用.razor方法:

@page "/navigate"
@inject NavigationManager MyNavigationManager

<h1>Current url</h1>

<p>@(MyNavigationManager.Uri)</p>

Run Code Online (Sandbox Code Playgroud)

编辑 于0.8.0,.cs已移至Uri命名空间.

  • @亨利罗德里格斯,不,你错了。正确的方法是注入IUriHelper,而不是实现.. (6认同)
  • 从 v0.8.0 开始,当使用服务器端模式时,你应该使用:`@inject Microsoft.AspNetCore.Components.Services.IUriHelper UriHelper`,当使用客户端模式时:`@inject Microsoft.AspNetCore.Blazor.Services.WebAssemblyUriHelper UriHelper` (2认同)
  • 备忘单非常有帮助+1 (2认同)

Jal*_*kum 10

首先,注入NavigationManager需要获取当前URL的组件,如下所示:

@inject NavigationManager NavManager
Run Code Online (Sandbox Code Playgroud)

现在使用以下行获取当前 URL:

string Url = NavManager.Uri.ToString();
Run Code Online (Sandbox Code Playgroud)


Flo*_*res 4

OnLocationChanged连接到页面或组件中的事件是没有用的,因为它们是根据需要加载和处理的。

您应该在 app.cshtml 中注册此事件,因为该事件不会被处理。