How to get component type from location/url/route

602 Views Asked by At

Scenario:

I have a Blazor Server Side app with basic routing and after navigation I need to check whether current page implements particular interface. e.g.:

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

Question:

How do I get the Component Type for current or a specific url/location?

2

There are 2 best solutions below

0
On BEST ANSWER

You can add an OnParametersSet method in your MainLayout component...

Also add: @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();
    
    
}
0
On

Not sure exactly what your trying to achieve but this may help:

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>

As the type of the page is now being passed as a cascading value you can:


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

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

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

I used two @If blocks here because your questions talks about interfaces however your example seems to be about a base type. One of the blocks should serve your needs.