Skip to content

Commit 7c2f475

Browse files
Improve the public Layout builder API (#608)
- Throw a more meaningful exception if the same segment is added twice to a layout - Do no longer prevent slashes in segment names but threat them as multiple segments
1 parent 26ca51f commit 7c2f475

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

Modules/Layouting/Provider/LayoutBuilder.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public LayoutBuilder Index(IHandlerBuilder handler)
4242
/// </summary>
4343
/// <param name="name">The name of the path segment to be handled</param>
4444
/// <param name="handler">The handler which will handle the segment</param>
45-
public LayoutBuilder Add(string name, IHandler handler) => Add(new HandlerWrapper(handler));
45+
public LayoutBuilder Add(string name, IHandler handler) => Add(name, new HandlerWrapper(handler));
4646

4747
/// <summary>
4848
/// Adds a handler that will be invoked for all URLs below
@@ -54,10 +54,14 @@ public LayoutBuilder Add(string name, IHandlerBuilder handler)
5454
{
5555
if (name.Contains('/'))
5656
{
57-
throw new ArgumentException("Path seperators are not allowed in the name of the segment.", nameof(name));
57+
return this.Add(name.Split('/', StringSplitOptions.RemoveEmptyEntries), handler);
58+
}
59+
60+
if (!RoutedHandlers.TryAdd(name, handler))
61+
{
62+
throw new InvalidOperationException($"A segment with the name '{name}' has already been added to the layout");
5863
}
5964

60-
RoutedHandlers.Add(name, handler);
6165
return this;
6266
}
6367

Testing/Acceptance/Modules/Layouting/LayoutTests.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,29 @@ public async Task TestRedirect(TestEngine engine)
8080
}
8181

8282
[TestMethod]
83-
[ExpectedException(typeof(ArgumentException))]
84-
public void TestIllegalPathCharacters()
83+
[MultiEngineTest]
84+
public async Task TestMultiSegmentInName(TestEngine engine)
8585
{
86-
Layout.Create().Add("some/path", Content.From(Resource.FromString("Hello World")));
86+
var layout = Layout.Create().Add("/api/v1/", Content.From(Resource.FromString("Hello World")));
87+
88+
await using var runner = await TestHost.RunAsync(layout, engine: engine);
89+
90+
using var response = await runner.GetResponseAsync("/api/v1/");
91+
92+
await response.AssertStatusAsync(HttpStatusCode.OK);
93+
94+
Assert.AreEqual("Hello World", await response.GetContentAsync());
95+
}
96+
97+
[TestMethod]
98+
public void TestSameSegmentTwice()
99+
{
100+
var content = Content.From(Resource.FromString("Hello World!"));
101+
102+
Assert.ThrowsException<InvalidOperationException>(() =>
103+
{
104+
Layout.Create().Add("one", content).Add("one", content);
105+
});
87106
}
88107

89108
[TestMethod]

0 commit comments

Comments
 (0)