Skip to content

Commit

Permalink
Improve the public Layout builder API (#608)
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
Kaliumhexacyanoferrat authored Jan 2, 2025
1 parent 26ca51f commit 7c2f475
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
10 changes: 7 additions & 3 deletions Modules/Layouting/Provider/LayoutBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public LayoutBuilder Index(IHandlerBuilder handler)
/// </summary>
/// <param name="name">The name of the path segment to be handled</param>
/// <param name="handler">The handler which will handle the segment</param>
public LayoutBuilder Add(string name, IHandler handler) => Add(new HandlerWrapper(handler));
public LayoutBuilder Add(string name, IHandler handler) => Add(name, new HandlerWrapper(handler));

/// <summary>
/// Adds a handler that will be invoked for all URLs below
Expand All @@ -54,10 +54,14 @@ public LayoutBuilder Add(string name, IHandlerBuilder handler)
{
if (name.Contains('/'))
{
throw new ArgumentException("Path seperators are not allowed in the name of the segment.", nameof(name));
return this.Add(name.Split('/', StringSplitOptions.RemoveEmptyEntries), handler);
}

if (!RoutedHandlers.TryAdd(name, handler))
{
throw new InvalidOperationException($"A segment with the name '{name}' has already been added to the layout");
}

RoutedHandlers.Add(name, handler);
return this;
}

Expand Down
25 changes: 22 additions & 3 deletions Testing/Acceptance/Modules/Layouting/LayoutTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,29 @@ public async Task TestRedirect(TestEngine engine)
}

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestIllegalPathCharacters()
[MultiEngineTest]
public async Task TestMultiSegmentInName(TestEngine engine)
{
Layout.Create().Add("some/path", Content.From(Resource.FromString("Hello World")));
var layout = Layout.Create().Add("/api/v1/", Content.From(Resource.FromString("Hello World")));

await using var runner = await TestHost.RunAsync(layout, engine: engine);

using var response = await runner.GetResponseAsync("/api/v1/");

await response.AssertStatusAsync(HttpStatusCode.OK);

Assert.AreEqual("Hello World", await response.GetContentAsync());
}

[TestMethod]
public void TestSameSegmentTwice()
{
var content = Content.From(Resource.FromString("Hello World!"));

Assert.ThrowsException<InvalidOperationException>(() =>
{
Layout.Create().Add("one", content).Add("one", content);
});
}

[TestMethod]
Expand Down

0 comments on commit 7c2f475

Please sign in to comment.