Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/OpenApi/src/Services/OpenApiDocumentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,12 @@ internal List<OpenApiServer> GetOpenApiServers(HttpRequest? httpRequest = null)
if (httpRequest is not null)
{
var serverUrl = UriHelper.BuildAbsolute(httpRequest.Scheme, httpRequest.Host, httpRequest.PathBase);
// Remove trailing slash when pathBase is empty to align with OpenAPI specification.
// Keep the trailing slash if pathBase explicitly contains "/" to preserve intentional path structure.
if (serverUrl.EndsWith('/') && !httpRequest.PathBase.HasValue)
{
serverUrl = serverUrl.TrimEnd('/');
}
return [new OpenApiServer { Url = serverUrl }];
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
},
"servers": [
{
"url": "http://localhost/"
"url": "http://localhost"
}
],
"paths": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public partial class OpenApiDocumentServiceTests
{
[Theory]
[InlineData("Development", "localhost:5001", "", "http", "http://localhost:5001/")]
[InlineData("Development", "localhost:5001", "", "http", "http://localhost:5001")]
[InlineData("Development", "example.com", "/api", "https", "https://example.com/api")]
[InlineData("Staging", "localhost:5002", "/v1", "http", "http://localhost:5002/v1")]
[InlineData("Staging", "api.example.com", "/base/path", "https", "https://api.example.com/base/path")]
Expand Down Expand Up @@ -145,4 +145,39 @@ public void GetOpenApiServers_HandlesServerAddressFeatureWithNoValues()
// Assert
Assert.Empty(servers);
}

[Fact]
public void GetOpenApiServers_RemovesTrailingSlashWhenPathBaseIsEmpty()
{
// Arrange
var hostEnvironment = new HostingEnvironment
{
ApplicationName = "TestApplication",
EnvironmentName = "Development"
};
var docService = new OpenApiDocumentService(
"v1",
new Mock<IApiDescriptionGroupCollectionProvider>().Object,
hostEnvironment,
GetMockOptionsMonitor(),
new Mock<IKeyedServiceProvider>().Object,
new OpenApiTestServer(["http://localhost:5000"]));
var httpContext = new DefaultHttpContext()
{
Request =
{
Host = new HostString("example.com"),
PathBase = "",
Scheme = "https"
}
};

// Act
var servers = docService.GetOpenApiServers(httpContext.Request);

// Assert
Assert.Single(servers);
Assert.Equal("https://example.com", servers[0].Url);
Assert.DoesNotContain("https://example.com/", servers.Select(s => s.Url));
}
}
Loading