blazor.net-5blazor-routing

How to get component type from location/url/route


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?


Solution

  • 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();
        
        
    }