Skip to content

Commit

Permalink
Merge pull request #885 from martincostello/Set-Content-Length
Browse files Browse the repository at this point in the history
Specify Content-Length when serializing JSON with System.Text.Json
  • Loading branch information
clairernovotny authored Apr 8, 2020
2 parents 3d6a764 + 31a62fe commit 02c856d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
20 changes: 20 additions & 0 deletions Refit.Tests/SerializedContentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,5 +146,25 @@ public async Task StreamDeserialization_UsingSystemTextJsonContentSerializer()
Assert.Equal(model.ShortNameForAlias, result.ShortNameForAlias);
Assert.Equal(model.ShortNameForJsonProperty, result.ShortNameForJsonProperty);
}

[Fact]
public async Task StreamDeserialization_UsingSystemTextJsonContentSerializer_SetsCorrectHeaders()
{
var model = new TestAliasObject
{
ShortNameForAlias = nameof(StreamDeserialization_UsingSystemTextJsonContentSerializer),
ShortNameForJsonProperty = nameof(TestAliasObject)
};

var serializer = new SystemTextJsonContentSerializer();

var json = await serializer.SerializeAsync(model);

Assert.NotNull(json.Headers.ContentLength);
Assert.True(json.Headers.ContentLength.Value > 0);
Assert.NotNull(json.Headers.ContentType);
Assert.Equal("utf-8", json.Headers.ContentType.CharSet);
Assert.Equal("application/json", json.Headers.ContentType.MediaType);
}
}
}
5 changes: 4 additions & 1 deletion Refit/SystemTextJsonContentSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@ public Task<HttpContent> SerializeAsync<T>(T item)

JsonSerializer.Serialize(utf8JsonWriter, item, jsonSerializerOptions);

var content = new StreamContent(utf8BufferWriter.DetachStream())
var stream = utf8BufferWriter.DetachStream();

var content = new StreamContent(stream)
{
Headers =
{
ContentLength = stream.Length,
ContentType = new MediaTypeHeaderValue("application/json") { CharSet = Encoding.UTF8.WebName }
}
};
Expand Down

0 comments on commit 02c856d

Please sign in to comment.