簡體   English   中英

在 Blazor 組件中獲取當前 URL

[英]Get current URL in a Blazor component

我需要知道當前頁面的 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;
        }
    }

我使用了與 Blazor 存儲庫中的 NavLink 組件相同的方法,但它不起作用。 有任何想法嗎?。

使用NavigationManager類中的Uri屬性。

這個怎么運作

.razor頁面上使用之前從注入中獲取它:

@inject NavigationManager MyNavigationManager

如果您更喜歡“代碼隱藏”體驗,或者像這樣在.cs文件中:

using Microsoft.AspNetCore.Components;
...
[Inject]
public NavigationManager MyNavigationManager {get; set;}

樣本

@page "/navigate"
@inject NavigationManager MyNavigationManager

<h1>Current URL</h1>

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

有關導航(NavigateTo、BaseUri、ToAbsoluteUri、ToBaseRelativePath、...)的更多信息,請參見: URI 和導航狀態助手

NavigationManager 備忘單

MyNavigationManager.Uri
#> https://localhost:5001/counter/3?q=hi

MyNavigationManager.BaseUri
#> https://localhost:5001/

MyNavigationManager.NavigateTo("http://new location")
#> Navigates to new location

MyNavigationManager.LocationChanged
#> An event that fires when the navigation location has changed.

MyNavigationManager.ToAbsoluteUri("pepe")
#> https://localhost:5001/pepe

MyNavigationManager.ToBaseRelativePath(MyNavigationManager.Uri)
#> counter/3?q=hi

Helper: AddQueryParm( "q2", "bye" ) // (*1)
#> https://localhost:5001/counter/3?q=hi&q2=bye

Helper: GetQueryParm( "q" )
#> hi

(*1) Net6 引入了GetUriWithQueryParameter 更多信息: 從 Blazor 操作查詢字符串

助手代碼:

@code {

    [Parameter]
    public string Id { get; set; }

    // Blazor: add parm to URL
    string AddQueryParm(string parmName, string parmValue)
    {
        var uriBuilder = new UriBuilder(MyNavigationManager.Uri);
        var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        q[parmName] = parmValue;
        uriBuilder.Query = q.ToString();
        var newUrl = uriBuilder.ToString();
        return newUrl;
    }

    // Blazor: get query parm from the URL
    string GetQueryParm(string parmName)
    {
        var uriBuilder = new UriBuilder(MyNavigationManager.Uri);
        var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        return q[parmName] ?? "";
    }

}

首先,將NavigationManager注入到需要獲取當前 URL 的組件中,如下所示:

@inject NavigationManager NavManager

現在使用以下行獲取當前 URL:

string Url = NavManager.Uri.ToString();

連接到頁面或組件中的OnLocationChanged事件是沒有用的,因為它們是按需加載和處置的。

您應該在 app.cshtml 中注冊此事件,因為它不會被釋放。

您應該聽 IUriHelper 的 LocationChange,它會觸發函數執行您想要的操作,例如:

@using Microsoft.AspNetCore.Blazor.Components
@using Microsoft.Extensions.Logging
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
@inject ILogger<NavItem> logger

<li class="m-menu__item @(Active ? "m-menu__item--active" : "")">
    <a href=@Url class="m-menu__link ">
        <span class="m-menu__item-here"></span>
        <i class="m-menu__link-icon @Icon"></i>
        <span class="m-menu__link-text">@Text</span>
    </a>
</li>

@functions {
    protected override void OnInit()
    {
        UriHelper.OnLocationChanged += OnLocationChanges;
    }
    [Parameter]
    private string Url { get; set; }
    [Parameter]
    private string Icon { get; set; }
    [Parameter]
    private string Text { get; set; }
    private bool Active = false;
    private void OnLocationChanges(object sender, string newLocation)
    {
        bool active = newLocation.Contains(Url);
        if(active != Active) //Only re-render the components that need it
        {
            Active = active;
            StateHasChanged();
            logger.LogInformation("Location Change To:" + newLocation);
        }
    }
}

在我的情況下,我只需要頁面的 Uri 而不是基本 Uri。

我將所有代碼保存在 razor.cs 文件中,因此我從代碼隱藏中注入 NavigationManager,如下所示:

[Inject] public NavigationManager Navigation { get; set; } 

Navigation.Uri 輸出:https://localhost:5001/nail-square-singel-shear-timber-timber

因此,要獲取頁面 Uri,只需執行以下操作:

Navigation.Uri.Replace(Navigation.BaseUri,"")

上述產量:釘-方形-單-剪切-木材-木材

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM