Skip to content

Commit 83c8b82

Browse files
committed
Fix #18539 - add Blazor catch-all route parameter
1 parent 4b94341 commit 83c8b82

File tree

6 files changed

+196
-17
lines changed

6 files changed

+196
-17
lines changed

src/Components/Components/src/Routing/RouteEntry.cs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,27 @@ public RouteEntry(RouteTemplate template, Type handler, string[] unusedRoutePara
2929

3030
internal void Match(RouteContext context)
3131
{
32+
string? catchAllValue = null;
33+
34+
// If this template contains a catch-all parameter, we can concatenate the pathSegments
35+
// at and beyond the catch-all segment's position. For example:
36+
// Template: /foo/bar/{*catchAll}
37+
// PathSegments: /foo/bar/one/two/three
38+
if (Template.ContainsCatchAllSegment && context.Segments.Length >= Template.Segments.Length)
39+
{
40+
if(Template.Segments.Last().EncodeSlashes)
41+
{
42+
catchAllValue = string.Join("%2F", context.Segments[Range.StartAt(Template.Segments.Length - 1)]);
43+
}
44+
else
45+
{
46+
catchAllValue = string.Join('/', context.Segments[Range.StartAt(Template.Segments.Length - 1)]);
47+
}
3248
// If there are no optional segments on the route and the length of the route
3349
// and the template do not match, then there is no chance of this matching and
3450
// we can bail early.
35-
if (Template.OptionalSegmentsCount == 0 && Template.Segments.Length != context.Segments.Length)
51+
}
52+
else if (Template.OptionalSegmentsCount == 0 && Template.Segments.Length != context.Segments.Length)
3653
{
3754
return;
3855
}
@@ -43,7 +60,15 @@ internal void Match(RouteContext context)
4360
for (var i = 0; i < Template.Segments.Length; i++)
4461
{
4562
var segment = Template.Segments[i];
46-
63+
64+
if (segment.IsCatchAll)
65+
{
66+
numMatchingSegments += 1;
67+
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
68+
parameters[segment.Value] = catchAllValue;
69+
break;
70+
}
71+
4772
// If the template contains more segments than the path, then
4873
// we may need to break out of this for-loop. This can happen
4974
// in one of two cases:
@@ -86,7 +111,7 @@ internal void Match(RouteContext context)
86111
// In addition to extracting parameter values from the URL, each route entry
87112
// also knows which other parameters should be supplied with null values. These
88113
// are parameters supplied by other route entries matching the same handler.
89-
if (UnusedRouteParameterNames.Length > 0)
114+
if (!Template.ContainsCatchAllSegment && UnusedRouteParameterNames.Length > 0)
90115
{
91116
parameters ??= new Dictionary<string, object>(StringComparer.Ordinal);
92117
for (var i = 0; i < UnusedRouteParameterNames.Length; i++)
@@ -116,7 +141,7 @@ internal void Match(RouteContext context)
116141
// `/this/is/a/template` and the route `/this/`. In that case, we want to ensure
117142
// that all non-optional segments have matched as well.
118143
var allNonOptionalSegmentsMatch = numMatchingSegments >= (Template.Segments.Length - Template.OptionalSegmentsCount);
119-
if (allRouteSegmentsMatch && allNonOptionalSegmentsMatch)
144+
if (Template.ContainsCatchAllSegment || (allRouteSegmentsMatch && allNonOptionalSegmentsMatch))
120145
{
121146
context.Parameters = parameters;
122147
context.Handler = Handler;

src/Components/Components/src/Routing/RouteTemplate.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,15 @@ public RouteTemplate(string templateText, TemplateSegment[] segments)
1515
TemplateText = templateText;
1616
Segments = segments;
1717
OptionalSegmentsCount = segments.Count(template => template.IsOptional);
18+
ContainsCatchAllSegment = segments.Any(template => template.IsCatchAll);
1819
}
1920

2021
public string TemplateText { get; }
2122

2223
public TemplateSegment[] Segments { get; }
2324

2425
public int OptionalSegmentsCount { get; }
26+
27+
public bool ContainsCatchAllSegment { get; }
2528
}
2629
}

src/Components/Components/src/Routing/TemplateParser.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ namespace Microsoft.AspNetCore.Components.Routing
1212
// The class in here just takes care of parsing a route and extracting
1313
// simple parameters from it.
1414
// Some differences with ASP.NET Core routes are:
15-
// * We don't support catch all parameter segments.
1615
// * We don't support complex segments.
1716
// The things that we support are:
1817
// * Literal path segments. (Like /Path/To/Some/Page)
1918
// * Parameter path segments (Like /Customer/{Id}/Orders/{OrderId})
19+
// * Catch-all parameters (Like /blog/{*slug})
2020
internal class TemplateParser
2121
{
2222
public static readonly char[] InvalidParameterNameCharacters =
23-
new char[] { '*', '{', '}', '=', '.' };
23+
new char[] { '{', '}', '=', '.' };
2424

2525
internal static RouteTemplate ParseTemplate(string template)
2626
{
@@ -80,6 +80,12 @@ internal static RouteTemplate ParseTemplate(string template)
8080
for (int i = 0; i < templateSegments.Length; i++)
8181
{
8282
var currentSegment = templateSegments[i];
83+
84+
if (currentSegment.IsCatchAll && i != templateSegments.Length - 1)
85+
{
86+
throw new InvalidOperationException($"Invalid template '{template}'. A catch-all parameter can only appear as the last segment of the route template.");
87+
}
88+
8389
if (!currentSegment.IsParameter)
8490
{
8591
continue;

src/Components/Components/src/Routing/TemplateSegment.cs

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,34 +12,45 @@ public TemplateSegment(string template, string segment, bool isParameter)
1212
{
1313
IsParameter = isParameter;
1414

15+
IsCatchAll = segment.StartsWith('*');
16+
17+
if (IsCatchAll)
18+
{
19+
// * > encodes slashes
20+
// ** > doesn't encode slashes
21+
EncodeSlashes = !segment.StartsWith("**");
22+
23+
Value = segment.TrimStart('*');
24+
}
25+
else
26+
{
27+
Value = segment;
28+
}
29+
1530
// Process segments that are not parameters or do not contain
1631
// a token separating a type constraint.
17-
if (!isParameter || segment.IndexOf(':') < 0)
32+
if (!isParameter || Value.IndexOf(':') < 0)
1833
{
1934
// Set the IsOptional flag to true for segments that contain
2035
// a parameter with no type constraints but optionality set
2136
// via the '?' token.
22-
if (segment.IndexOf('?') == segment.Length - 1)
37+
if (Value.IndexOf('?') == Value.Length - 1)
2338
{
2439
IsOptional = true;
25-
Value = segment.Substring(0, segment.Length - 1);
40+
Value = Value.Substring(0, Value.Length - 1);
2641
}
2742
// If the `?` optional marker shows up in the segment but not at the very end,
2843
// then throw an error.
29-
else if (segment.IndexOf('?') >= 0 && segment.IndexOf('?') != segment.Length - 1)
44+
else if (Value.IndexOf('?') >= 0 && Value.IndexOf('?') != Value.Length - 1)
3045
{
3146
throw new ArgumentException($"Malformed parameter '{segment}' in route '{template}'. '?' character can only appear at the end of parameter name.");
3247
}
33-
else
34-
{
35-
Value = segment;
36-
}
37-
48+
3849
Constraints = Array.Empty<RouteConstraint>();
3950
}
4051
else
4152
{
42-
var tokens = segment.Split(':');
53+
var tokens = Value.Split(':');
4354
if (tokens[0].Length == 0)
4455
{
4556
throw new ArgumentException($"Malformed parameter '{segment}' in route '{template}' has no name before the constraints list.");
@@ -54,6 +65,21 @@ public TemplateSegment(string template, string segment, bool isParameter)
5465
.Select(token => RouteConstraint.Parse(template, segment, token))
5566
.ToArray();
5667
}
68+
69+
if (IsParameter)
70+
{
71+
if (IsOptional && IsCatchAll)
72+
{
73+
throw new InvalidOperationException($"Invalid segment '{segment}' in route '{template}'. A catch-all parameter cannot be marked optional.");
74+
}
75+
76+
// Moving the check for this here instead of TemplateParser so we can allow catch-all.
77+
var invalidCharacter = Value.IndexOf('*');
78+
if (invalidCharacter != -1)
79+
{
80+
throw new InvalidOperationException($"Invalid template '{template}'. The character '{segment[invalidCharacter]}' in parameter segment '{{{segment}}}' is not allowed.");
81+
}
82+
}
5783
}
5884

5985
// The value of the segment. The exact text to match when is a literal.
@@ -64,6 +90,11 @@ public TemplateSegment(string template, string segment, bool isParameter)
6490

6591
public bool IsOptional { get; }
6692

93+
public bool IsCatchAll { get; }
94+
95+
// When true, slashes in a catchAll parameter will be encoded.
96+
public bool EncodeSlashes { get; }
97+
6798
public RouteConstraint[] Constraints { get; }
6899

69100
public bool Match(string pathSegment, out object? matchedParameterValue)

src/Components/Components/test/Routing/RouteTableFactoryTests.cs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,41 @@ public void CanMatchParameterTemplate(string path, string expectedValue)
226226
Assert.Single(context.Parameters, p => p.Key == "parameter" && (string)p.Value == expectedValue);
227227
}
228228

229+
[Theory]
230+
[InlineData("/blog/value1", "value1")]
231+
[InlineData("/blog/value1/test", "value1%2Ftest")]
232+
public void CanMatchCatchAllParameterTemplate_WhenEncodeSlashes_IsTrue(string path, string expectedValue)
233+
{
234+
// Arrange
235+
var routeTable = new TestRouteTableBuilder().AddRoute("/blog/{*parameter}").Build();
236+
var context = new RouteContext(path);
237+
238+
// Act
239+
routeTable.Route(context);
240+
241+
// Assert
242+
Assert.NotNull(context.Handler);
243+
Assert.Single(context.Parameters, p => p.Key == "parameter" && (string)p.Value == expectedValue);
244+
}
245+
246+
247+
[Theory]
248+
[InlineData("/blog/value1", "value1")]
249+
[InlineData("/blog/value1/test", "value1/test")]
250+
public void CanMatchCatchAllParameterTemplate_WhenEncodeSlashes_IsFalse(string path, string expectedValue)
251+
{
252+
// Arrange
253+
var routeTable = new TestRouteTableBuilder().AddRoute("/blog/{**parameter}").Build();
254+
var context = new RouteContext(path);
255+
256+
// Act
257+
routeTable.Route(context);
258+
259+
// Assert
260+
Assert.NotNull(context.Handler);
261+
Assert.Single(context.Parameters, p => p.Key == "parameter" && (string)p.Value == expectedValue);
262+
}
263+
229264
[Fact]
230265
public void CanMatchTemplateWithMultipleParameters()
231266
{
@@ -247,6 +282,29 @@ public void CanMatchTemplateWithMultipleParameters()
247282
Assert.Equal(expectedParameters, context.Parameters);
248283
}
249284

285+
286+
[Fact]
287+
public void CanMatchTemplateWithMultipleParametersAndCatchAllParameter()
288+
{
289+
// Arrange
290+
var routeTable = new TestRouteTableBuilder().AddRoute("/{some}/awesome/{route}/with/{**catchAll}").Build();
291+
var context = new RouteContext("/an/awesome/path/with/some/catch/all/stuff");
292+
293+
var expectedParameters = new Dictionary<string, object>
294+
{
295+
["some"] = "an",
296+
["route"] = "path",
297+
["catchAll"] = "some/catch/all/stuff"
298+
};
299+
300+
// Act
301+
routeTable.Route(context);
302+
303+
// Assert
304+
Assert.NotNull(context.Handler);
305+
Assert.Equal(expectedParameters, context.Parameters);
306+
}
307+
250308
public static IEnumerable<object[]> CanMatchParameterWithConstraintCases() => new object[][]
251309
{
252310
new object[] { "/{value:bool}", "/true", true },

src/Components/Components/test/Routing/TemplateParserTests.cs

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,51 @@ public void Parse_MultipleOptionalParameters()
8383
Assert.Equal(expected, actual, RouteTemplateTestComparer.Instance);
8484
}
8585

86+
[Theory]
87+
[InlineData("{*p}")]
88+
[InlineData("{**p}")]
89+
public void Parse_SingleCatchAllParameter(string template)
90+
{
91+
// Arrange
92+
var expected = new ExpectedTemplateBuilder().Parameter("p");
93+
94+
// Act
95+
var actual = TemplateParser.ParseTemplate(template);
96+
97+
// Assert
98+
Assert.Equal(expected, actual, RouteTemplateTestComparer.Instance);
99+
}
100+
101+
[Theory]
102+
[InlineData("awesome/wow/{*p}")]
103+
[InlineData("awesome/wow/{**p}")]
104+
public void Parse_MixedLiteralAndCatchAllParameter(string template)
105+
{
106+
// Arrange
107+
var expected = new ExpectedTemplateBuilder().Literal("awesome").Literal("wow").Parameter("p");
108+
109+
// Act
110+
var actual = TemplateParser.ParseTemplate(template);
111+
112+
// Assert
113+
Assert.Equal(expected, actual, RouteTemplateTestComparer.Instance);
114+
}
115+
116+
[Theory]
117+
[InlineData("awesome/{p1}/{*p2}")]
118+
[InlineData("awesome/{p1}/{**p2}")]
119+
public void Parse_MixedLiteralParameterAndCatchAllParameter(string template)
120+
{
121+
// Arrange
122+
var expected = new ExpectedTemplateBuilder().Literal("awesome").Parameter("p1").Parameter("p2");
123+
124+
// Act
125+
var actual = TemplateParser.ParseTemplate(template);
126+
127+
// Assert
128+
Assert.Equal(expected, actual, RouteTemplateTestComparer.Instance);
129+
}
130+
86131
[Fact]
87132
public void InvalidTemplate_WithRepeatedParameter()
88133
{
@@ -113,7 +158,8 @@ public void InvalidTemplate_WithMismatchedBraces(string template, string expecte
113158
}
114159

115160
[Theory]
116-
[InlineData("{*}", "Invalid template '{*}'. The character '*' in parameter segment '{*}' is not allowed.")]
161+
// * is only allowed at beginning for catch-all parameters
162+
[InlineData("{p*}", "Invalid template '{p*}'. The character '*' in parameter segment '{p*}' is not allowed.")]
117163
[InlineData("{{}", "Invalid template '{{}'. The character '{' in parameter segment '{{}' is not allowed.")]
118164
[InlineData("{}}", "Invalid template '{}}'. The character '}' in parameter segment '{}}' is not allowed.")]
119165
[InlineData("{=}", "Invalid template '{=}'. The character '=' in parameter segment '{=}' is not allowed.")]
@@ -166,6 +212,16 @@ public void InvalidTemplate_NonOptionalParamAfterOptionalParam()
166212
Assert.Equal(expectedMessage, ex.Message);
167213
}
168214

215+
[Fact]
216+
public void InvalidTemplate_CatchAllParamNotLast()
217+
{
218+
var ex = Assert.Throws<InvalidOperationException>(() => TemplateParser.ParseTemplate("/test/{*a}/{b}"));
219+
220+
var expectedMessage = "Invalid template 'test/{*a}/{b}'. A catch-all parameter can only appear as the last segment of the route template.";
221+
222+
Assert.Equal(expectedMessage, ex.Message);
223+
}
224+
169225
[Fact]
170226
public void InvalidTemplate_BadOptionalCharacterPosition()
171227
{

0 commit comments

Comments
 (0)