Skip to content

Conversation

@AustinWise
Copy link

This PR applies to the generated code for clients when using System.Text.Json serialization library.

This PR uses the JsonContent class to send objects as the request body. This is the documented way to serialize objects when making HTTP requests. It can be more efficient than serializing the entire request body into a byte array, particularly if the request body is large. This is because the JsonContent can stream the body while serializing and reuse buffers between requests.

In terms of the backwards compatibility impact of this change, the documentation says JsonContent was added in .NET 5. When running on .NET Framework, a reference to the System.Net.Http.Json Nuget package would now be required.

Contributes to #4083

@AustinWise
Copy link
Author

I tested this PR with OpenAPI specification for Ollama I'm using. I confirmed that:

  • Code generation is unchanged when using NewtonSoft.
  • The code compiles and sends a request successfully with the new System.Text.Json code generation.

Here is what a diff of the generated code looks like:

                 using (var request_ = new System.Net.Http.HttpRequestMessage())
                 {
-                    var json_ = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(body, JsonSerializerSettings);
-                    var content_ = new System.Net.Http.ByteArrayContent(json_);
-                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
+                    var content_ = System.Net.Http.Json.JsonContent.Create(body, System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"), JsonSerializerSettings);
                     request_.Content = content_;

@AustinWise AustinWise marked this pull request as ready for review February 9, 2025 05:32
@RicoSuter
Copy link
Owner

Thanks for the PR.
Is this behaving exactly the same? Is this only available with newer .NET versions?

@AustinWise
Copy link
Author

I added some snapshot tests to ensure the generated code compiles.

Is this behaving exactly the same?

I believe so. I ensured that that Content-Type header is the same. The implementation of JsonContent is pretty small, ultimately it also calls into JsonSerializer, see here.

One change is users targeting .NET Standard or .NET Framework will have to add a reference to the System.Net.Http.Json Nuget package.

Is this only available with newer .NET versions?

The JsonConten type has been include with .NET since version 5. When targeting .NET Standard or .NET Framework, the package that provides the type has the same supported frameworks as the package that provides the main System.Text.Json serializer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants