Skip to content
Merged
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: 4 additions & 2 deletions src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,9 @@ SecurityException or

private static string InspectInputFormat(string input)
{
return input.StartsWith("{", StringComparison.OrdinalIgnoreCase) || input.StartsWith("[", StringComparison.OrdinalIgnoreCase) ? OpenApiConstants.Json : OpenApiConstants.Yaml;
var trimmedInput = input.TrimStart();
return trimmedInput.StartsWith("{", StringComparison.OrdinalIgnoreCase) || trimmedInput.StartsWith("[", StringComparison.OrdinalIgnoreCase) ?
OpenApiConstants.Json : OpenApiConstants.Yaml;
}

/// <summary>
Expand Down Expand Up @@ -393,7 +395,7 @@ private static bool TryInspectStreamFormat(Stream stream, out string? format)
var firstByte = (char)stream.ReadByte();

// Skip whitespace if present and read the next non-whitespace byte
if (char.IsWhiteSpace(firstByte))
while (char.IsWhiteSpace(firstByte))
{
firstByte = (char)stream.ReadByte();
}
Expand Down
26 changes: 26 additions & 0 deletions test/Microsoft.OpenApi.Tests/Reader/OpenApiModelFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,32 @@ public async Task CanLoadAnAsyncOnlyStreamInYamlAndDetectFormat()
Assert.Equal("Sample API", document.Info.Title);
}

[Fact]
public async Task CanLoadANonSeekableStreamInJsonAndDetectFormatWhenPrecededBySpaces()
{
// Given
using var memoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(" " + documentJson));
using var nonSeekableStream = new NonSeekableStream(memoryStream);

// When
var (document, _) = await OpenApiDocument.LoadAsync(nonSeekableStream);

// Then
Assert.NotNull(document);
Assert.Equal("Sample API", document.Info.Title);
}

[Fact]
public void CanLoadAStringJsonAndDetectFormatWhenPrecededBySpaces()
{
// When
var (document, _) = OpenApiDocument.Parse(" " + documentJson);

// Then
Assert.NotNull(document);
Assert.Equal("Sample API", document.Info.Title);
}

public sealed class AsyncOnlyStream : Stream
{
private readonly Stream _innerStream;
Expand Down