【问题标题】:Blazor middleware to run after navigating to any page导航到任何页面后要运行的 Blazor 中间件
【发布时间】:2021-03-09 09:14:47
【问题描述】:

我编写了一个中间件类,但目前仅在我启动应用程序时运行,我希望它在每次应用程序导航到不同页面时运行。

谢谢!

【问题讨论】:

  • 您好,可以提供minimal reproducible example吗?
  • SPA = "单页" 应用程序,从服务器的角度来看,您只能导航到一页。页面导航在 SPA 内部。这是服务器端还是 wasm?
  • 这是 blazor 服务器。

标签: asp.net-core blazor middleware


【解决方案1】:

对于这种类型的中间件,您必须使用 NavigationManager.LocationChanged 事件,因为 Blazor 使用 websocket 来呈现 UI,而不是您所期望的传统 HTTP 请求。 MainLayout.razor 或任何只会呈现一次的组件的示例:

@implements IDisposable
@inject NavigationManager NavMgr

<h1>My Component</h1>
@code
{
    public OnInitialized()
    {
        // Bind the LocationChanged event
        NavMgr.LocationChanged += OnLocationChanged;
    }
    private void OnLocationChanged(object sender, LocationChangedEventArgs args)
    {
       // My code to execute when navigation has changed
    }
    public void Dispose()
    {
        // Always unbind the event on component disposal
        NavMgr.LocationChanged -= OnLocationChanged;   
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2021-06-07
    • 1970-01-01
    • 2020-05-23
    • 2019-06-05
    • 2021-05-10
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多