Blazor 替换浏览器历史记录中的 URL

Ala*_*ref 5 blazor blazor-server-side

导航到另一个页面时,Blazor 路由是否有办法替换 URL 链接?类似于 JS 中的 window.location.replace,或者 React 的“Link”标签中的 replace 属性,或者 React 的 history.replace?我不想在应用程序中的每个导航中都有一个历史记录项目..

更新:我在索引页面中尝试了以下内容,但无济于事:

@inject IJSRuntime js
@inject NavigationManager NavigationManager
protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += LocationChanged;
        base.OnInitialized();
    }
    private void LocationChanged(object sender, LocationChangedEventArgs e)
    {
        js.InvokeVoidAsync("replace", e.Location);
    }
Run Code Online (Sandbox Code Playgroud)

而js函数是:

function replace(url) {
    window.location.replace(url);
}
Run Code Online (Sandbox Code Playgroud)

d.i*_*joe 5

从 ASP.Net Core 6.0 开始,NagivationManager 的 NavigateTo 方法出现重载

NavigateTo (string uri, bool forceLoad = false, bool replace = false)
Run Code Online (Sandbox Code Playgroud)

您可以在其中将替换参数设置为 true 以替换历史堆栈中的当前条目。


Mu-*_*sai 4

这个功能实际上是在 JS 互操作中提供的,但不知何故在NavigationManager撰写本答案时并未提供。所以你需要做的是直接调用JS函数:

js.InvokeVoidAsync("Blazor._internal.navigationManager.navigateTo", yourReletiveUrl, false, true);
Run Code Online (Sandbox Code Playgroud)

这里第三个参数指定它应该替换历史记录而不是推送它。