in src/Microsoft.OpenApi/Models/OpenApiDocument.cs [255:319]
private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer> servers)
{
if (servers == null || !servers.Any())
{
return;
}
// Arbitrarily choose the first server given that V2 only allows
// one host, port, and base path.
var firstServer = servers.First();
// Divide the URL in the Url property into host and basePath required in OpenAPI V2
// The Url property cannotcontain path templating to be valid for V2 serialization.
var firstServerUrl = new Uri(firstServer.Url, UriKind.RelativeOrAbsolute);
// host
if (firstServerUrl.IsAbsoluteUri)
{
writer.WriteProperty(
OpenApiConstants.Host,
firstServerUrl.GetComponents(UriComponents.Host | UriComponents.Port, UriFormat.SafeUnescaped));
// basePath
if (firstServerUrl.AbsolutePath != "/")
{
writer.WriteProperty(OpenApiConstants.BasePath, firstServerUrl.AbsolutePath);
}
} else
{
var relativeUrl = firstServerUrl.OriginalString;
if (relativeUrl.StartsWith("//"))
{
var pathPosition = relativeUrl.IndexOf('/', 3);
writer.WriteProperty(OpenApiConstants.Host, relativeUrl.Substring(0, pathPosition));
relativeUrl = relativeUrl.Substring(pathPosition);
}
if (!String.IsNullOrEmpty(relativeUrl) && relativeUrl != "/")
{
writer.WriteProperty(OpenApiConstants.BasePath, relativeUrl);
}
}
// Consider all schemes of the URLs in the server list that have the same
// host, port, and base path as the first server.
var schemes = servers.Select(
s =>
{
Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url);
return url;
})
.Where(
u => Uri.Compare(
u,
firstServerUrl,
UriComponents.Host | UriComponents.Port | UriComponents.Path,
UriFormat.SafeUnescaped,
StringComparison.OrdinalIgnoreCase) ==
0 && u.IsAbsoluteUri)
.Select(u => u.Scheme)
.Distinct()
.ToList();
// schemes
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) => w.WriteValue(s));
}