Skip to content

Commit ff22ab9

Browse files
Merge pull request #1835 from chelkyl/chelkyl/support-trailing-slashes
Support trailing slashes in paths
2 parents faa13eb + e18748f commit ff22ab9

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,13 @@ public OpenApiUrlTreeNode Attach(string path,
150150
}
151151

152152
var segments = path.Split('/');
153+
if (path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
154+
{
155+
// Remove the last element, which is empty, and append the trailing slash to the new last element
156+
// This is to support URLs with trailing slashes
157+
Array.Resize(ref segments, segments.Length - 1);
158+
segments[segments.Length - 1] += @"\";
159+
}
153160

154161
return Attach(segments: segments,
155162
pathItem: pathItem,

test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,5 +466,38 @@ public async Task VerifyDiagramFromSampleOpenAPIAsync()
466466

467467
await Verifier.Verify(diagram);
468468
}
469+
470+
public static TheoryData<string, string[], string, string> SupportsTrailingSlashesInPathData => new TheoryData<string, string[], string, string>
471+
{
472+
// Path, children up to second to leaf, last expected leaf node name, expected leaf node path
473+
{ "/cars/{car-id}/build/", ["cars", "{car-id}"], @"build\", @"\cars\{car-id}\build\" },
474+
{ "/cars/", [], @"cars\", @"\cars\" },
475+
};
476+
477+
[Theory]
478+
[MemberData(nameof(SupportsTrailingSlashesInPathData))]
479+
public void SupportsTrailingSlashesInPath(string path, string[] childrenBeforeLastNode, string expectedLeafNodeName, string expectedLeafNodePath)
480+
{
481+
var openApiDocument = new OpenApiDocument
482+
{
483+
Paths = new()
484+
{
485+
[path] = new()
486+
}
487+
};
488+
489+
var label = "trailing-slash";
490+
var rootNode = OpenApiUrlTreeNode.Create(openApiDocument, label);
491+
492+
var secondToLeafNode = rootNode;
493+
foreach (var childName in childrenBeforeLastNode)
494+
{
495+
secondToLeafNode = secondToLeafNode.Children[childName];
496+
}
497+
498+
Assert.True(secondToLeafNode.Children.TryGetValue(expectedLeafNodeName, out var leafNode));
499+
Assert.Equal(expectedLeafNodePath, leafNode.Path);
500+
Assert.Empty(leafNode.Children);
501+
}
469502
}
470503
}

0 commit comments

Comments
 (0)