如何从位置/ URL /路线获取组件类型

时间:2020-10-20 12:24:14

标签: blazor .net-5 blazor-routing

场景:

我有一个带有基本路由的Blazor服务器端应用程序,导航后,我需要检查当前页面是否实现了特定的界面。 例如:

NavigationService.LocationChanged += (sender, args) => 
{
  Type componentType = GetComponetFromLocation(args.Location);
  if (!componentType.GetInterfaces().Contains(typeof(PageBase)) {
  }
}

问题:

如何获取当前或特定网址/位置的组件类型?

2 个答案:

答案 0 :(得分:2)

不确定要达到的目标,但这可能会有所帮助:

App.razor

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <CascadingValue Value="@routeData.PageType" Name="PageType" >
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </CascadingValue>
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

随着页面类型现在作为级联值传递,您可以:


@if(!PageType.IsSubclassOf(typeof(PageBase)))
{
    <div> ... </div>
}

@if(PageType.GetInterface("PageBase") == null)
{
    <div> ... </div>
}

@code {
    [CascadingParameter(Name="PageType")]
    public Type PageType { get; set; }
}

我在这里使用了两个@If块,因为您的问题是关于接口的,但是您的示例似乎是关于基本类型的。其中之一应该满足您的需求。

答案 1 :(得分:1)

您可以在MainLayout组件中添加OnParametersSet方法...

还添加:@using System.Reflection;

protected override void OnParametersSet()
{
    // Get the Component Type from the route data
    var component = (this.Body.Target as RouteView)?.RouteData.PageType;

    // Get a list of all the interfaces implemented by the component. 
    // It should be: IComponent, IHandleEvent, IHandleAfterRender,
    // Unless your routable component has derived from ComponentBase,
    // and added interface implementations of its own  
    var allInterfaces = component.GetInterfaces();
    
    
}