Fallback for Components router (imported from Blazor PR 1534) (#4794)

This commit is contained in:
Steve Sanderson 2018-12-14 17:06:47 +00:00 committed by GitHub
parent e768a78c2b
commit 3757908b14
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 3 deletions

View File

@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Layouts;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Services;
@ -30,6 +29,11 @@ namespace Microsoft.AspNetCore.Components.Routing
/// assemblies, for components matching the URI.
/// </summary>
[Parameter] private Assembly AppAssembly { get; set; }
/// <summary>
/// Gets or sets the type of the component that should be used as a fallback when no match is found for the requested route.
/// </summary>
[Parameter] private Type FallbackComponent { get; set; }
private RouteTable Routes { get; set; }
@ -80,9 +84,17 @@ namespace Microsoft.AspNetCore.Components.Routing
locationPath = StringUntilAny(locationPath, _queryOrHashStartChar);
var context = new RouteContext(locationPath);
Routes.Route(context);
if (context.Handler == null)
{
throw new InvalidOperationException($"'{nameof(Router)}' cannot find any component with a route for '/{locationPath}'.");
if (FallbackComponent != null)
{
context.Handler = FallbackComponent;
}
else
{
throw new InvalidOperationException($"'{nameof(Router)}' cannot find any component with a route for '/{locationPath}', and no fallback is defined.");
}
}
if (!typeof(IComponent).IsAssignableFrom(context.Handler))

View File

@ -88,6 +88,15 @@ namespace Microsoft.AspNetCore.Components.E2ETest.Tests
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
[Fact]
public void CanArriveAtFallbackPageFromBadURI()
{
SetUrlViaPushState("/Oopsie_Daisies%20%This_Aint_A_Real_Page");
var app = MountTestComponent<TestRouter>();
Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanFollowLinkToOtherPage()
{

View File

@ -0,0 +1 @@
<div id="test-info">Oops, that component wasn't found!</div>

View File

@ -1 +1 @@
<Router AppAssembly=typeof(BasicTestApp.Program).Assembly />
<Router AppAssembly=typeof(BasicTestApp.Program).Assembly FallbackComponent="typeof(Error404)" />