From 31a62fe6fd4b4dbf666a5a1859c991c795c5bd54 Mon Sep 17 00:00:00 2001 From: martincostello Date: Thu, 2 Apr 2020 11:15:54 +0100 Subject: [PATCH] Specify Content-Length when serializing JSON Specify the Content-Length, as it is known, when serializing JSON using System.Text.Json for compatibility with systems that do not support chunked encoding. --- Refit.Tests/SerializedContentTests.cs | 20 ++++++++++++++++++++ Refit/SystemTextJsonContentSerializer.cs | 5 ++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Refit.Tests/SerializedContentTests.cs b/Refit.Tests/SerializedContentTests.cs index 2477720ab..674a82dcb 100644 --- a/Refit.Tests/SerializedContentTests.cs +++ b/Refit.Tests/SerializedContentTests.cs @@ -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); + } } } diff --git a/Refit/SystemTextJsonContentSerializer.cs b/Refit/SystemTextJsonContentSerializer.cs index e40cf9f50..93f5efe48 100644 --- a/Refit/SystemTextJsonContentSerializer.cs +++ b/Refit/SystemTextJsonContentSerializer.cs @@ -44,10 +44,13 @@ public Task SerializeAsync(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 } } };