在Blazor组件中获取当前的网址 [英] Get current Url in a Blazor component
本文介绍了在Blazor组件中获取当前的网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要知道当前页面的网址,以检查是否必须对元素应用某些样式.下面的代码是一个示例.
I need to know the url of the current page in order to check if I have to apply certain style to a element. The code below is an example.
@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;
}
}
我使用了Blazor信息库中NavLink组件中使用的相同方法,但是没有用.有什么想法吗?
I used the same approach used in the NavLink component in the Blazor repository, but it did not work. Any ideas?.
推荐答案
使用 NavigationManager
类中的 Uri
属性.
Use Uri
property from NavigationManager
class.
从注入中获取它,然后才能在.razor
页上使用它:
Get it from injection before to use it on .razor
pages:
@inject NavigationManager MyNavigationManager
或者,如果您更喜欢代码隐藏"体验,请在.cs
上这样:
Or like this on .cs
if you prefer "code-behind" experience:
using Microsoft.AspNetCore.Components;
...
[Inject]
public NavigationManager MyNavigationManager {get; set;}
样本
@page "/navigate"
@inject NavigationManager MyNavigationManager
<h1>Current url</h1>
<p>@(MyNavigationManager.Uri)</p>
查看全文