Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use JsonContent when creating request bodies #5102

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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
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.

1 participant