场景:
我有一个Blazor Server Side应用程序,它有基本的路由,导航后我需要检查当前页面是否实现了特定的接口。例如:
NavigationService.LocationChanged += (sender, args) =>
{
Type componentType = GetComponetFromLocation(args.Location);
if (!componentType.GetInterfaces().Contains(typeof(PageBase)) {
}
}
问题:
如何获取当前或特定url/位置的组件类型?
不确定你想要实现什么,但这可能会有所帮助:
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
块,因为您的问题涉及接口,但是您的示例似乎是关于基类型的。其中一块应该能满足你的需求。
您可以在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();
}