From b12c0578f471082a9db4ce58f0bd1a9466d172ac Mon Sep 17 00:00:00 2001 From: 2ynn Date: Mon, 9 Nov 2026 20:24:30 -0500 Subject: [PATCH 1/3] fix(csharp): send union-typed fields in form-urlencoded request bodies A form field whose schema is a union was sent under an empty key: the union wrapper was walked like a regular object, and its variant properties carry form metadata without a name. Servers dropped the field. SerializeFormValue now detects a union wrapper and encodes its active variant under the field's name, applying the field's explode setting. A union with no active variant (null, or an open union holding an unknown value) is omitted. IsUnionWrapper moves from UnionDeserializer, which is only emitted for the populated-fields union strategy, to Utilities. Adds a primary fragment covering scalar, enum, array, nullable, unset and JSON-encoded union fields, with C# runtime tests against the echo server. --- .changesets/1794266812-8cefc478.yaml | 10 ++ templates/perms.go | 1 + .../Utils/RequestBodySerializer.cs.stmpl | 30 +++++- .../Utils/UnionDeserializer.cs.stmpl | 17 +--- .../Utils/Utilities.cs.stmpl | 11 +++ .../FormUnionFieldsAdditionalShould.cs | 75 ++++++++++++++ .../fragments/primary/form-union-fields.yaml | 97 +++++++++++++++++++ zSDKs/sdk-csharp/.speakeasy/gen.lock | 6 +- .../OpenAPI/Utils/RequestBodySerializer.cs | 30 +++++- .../OpenAPI/Utils/UnionDeserializer.cs | 16 +-- .../src/Speakeasy/OpenAPI/Utils/Utilities.cs | 10 ++ 11 files changed, 271 insertions(+), 32 deletions(-) create mode 100644 .changesets/1794266812-8cefc478.yaml create mode 100644 templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs create mode 100644 tests/specs/fragments/primary/form-union-fields.yaml diff --git a/.changesets/1794266812-8cefc478.yaml b/.changesets/1794266812-8cefc478.yaml new file mode 100644 index 000000000..ceb426c52 --- /dev/null +++ b/.changesets/1794266812-8cefc478.yaml @@ -0,0 +1,10 @@ +id: 1794266812-8cefc478 +features: + - core +targets: + - csharp +type: fix +bump: patch +description: send union-typed fields in form-urlencoded request bodies +author: 2ynn +date: "2026-11-09" diff --git a/templates/perms.go b/templates/perms.go index 2cc4923d4..8ca8cde1f 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -492,6 +492,7 @@ var fileMode = map[string]fs.FileMode{ "templates/csharp/tests/primary/ErrorsShould.cs": 0o644, "templates/csharp/tests/primary/EventStreamAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/FlatteningShould.cs": 0o644, + "templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/GlobalsAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/HeadersShould.cs": 0o644, "templates/csharp/tests/primary/Helpers.cs": 0o644, diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl index d9b5a2805..ccf56ee28 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl @@ -348,7 +348,15 @@ namespace {{getScopeNamespace "utils"}} ref Dictionary> form ) { - if (Utilities.IsClass(value)) + if (Utilities.IsUnionWrapper(value.GetType())) + { + var variant = GetUnionVariantValue(value); + if (variant != null) + { + SerializeFormValue(fieldName, explode, variant, ref form); + } + } + else if (Utilities.IsClass(value)) { if (Utilities.IsDate(value)) { @@ -508,6 +516,26 @@ namespace {{getScopeNamespace "utils"}} } } + private static object? GetUnionVariantValue(object union) + { + foreach (var prop in union.GetType().GetProperties()) + { + var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); + if (metadata == null || metadata.Name != "") + { + continue; + } + + var val = {{ templateGetPropValue "union" }}; + if (val != null) + { + return val; + } + } + + return null; + } + private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject) { byte[]? content = null; diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl index 79e23c59b..0ab088816 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl @@ -140,7 +140,7 @@ namespace {{getScopeNamespace "utils"}} private static bool PreCheck(JToken json, Type type) { if (json.Type != JTokenType.Object) return true; - if (IsUnionWrapper(type)) return true; + if (Utilities.IsUnionWrapper(type)) return true; var jo = (JObject)json; foreach (var (prop, attr) in EnumerateJsonProperties(type)) @@ -202,7 +202,7 @@ namespace {{getScopeNamespace "utils"}} return; } - if (IsUnionWrapper(type) && value != null) + if (Utilities.IsUnionWrapper(type) && value != null) { var (variantType, variantValue) = FindActiveVariant(type, value); if (variantValue != null) @@ -392,23 +392,12 @@ namespace {{getScopeNamespace "utils"}} return t; } - // A union wrapper is a class generated by speakeasy that carries the - // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant - // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). - private static bool IsUnionWrapper(Type type) - { - var attr = type.GetCustomAttribute(); - if (attr == null) return false; - return attr.ConverterType != null - && attr.ConverterType.DeclaringType == type; - } - {{- if hasAnyOpenUnion}} // True when the value is an open union wrapper that fell back to its Unknown sentinel private static bool IsUnknownUnionValue(Type type, object? value) { - if (value == null || !IsUnionWrapper(type)) return false; + if (value == null || !Utilities.IsUnionWrapper(type)) return false; return value is IOpenUnion openUnion && openUnion.IsUnknown(); } {{- end}} diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl index 163f96c96..96533e8d8 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl @@ -181,6 +181,17 @@ namespace {{getScopeNamespace "utils"}} public static bool IsOpenEnum(object? o) => o is IOpenEnum; + // A union wrapper is a class generated by speakeasy that carries the + // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant + // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). + public static bool IsUnionWrapper(Type type) + { + var attr = Attribute.GetCustomAttribute(type, typeof(JsonConverterAttribute)) as JsonConverterAttribute; + if (attr == null) return false; + return attr.ConverterType != null + && attr.ConverterType.DeclaringType == type; + } + public static bool IsClass(object? o) { if (o == null) diff --git a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs new file mode 100644 index 000000000..d534aa729 --- /dev/null +++ b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs @@ -0,0 +1,75 @@ +#nullable enable +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using Openapi; +using Openapi.Models.Shared; +using Xunit; + +public class FormUnionFieldsAdditionalShould +{ + private const string FormExplodedArrayKeySuffix = "[]"; + + [Fact] + public async Task SendStringEnumAndJsonVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + StringOrArrayUnion = FormUnionStringOrArray.CreateStr("solo"), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateFormUnionEnum(FormUnionEnum.Second), + NullableUnion = FormUnionNullable.CreateNull(), + JsonUnion = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "x", + Count = 1, + }), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.Object!.Form!; + + Assert.Equal("abc", form["scalarUnion"]); + Assert.Equal("solo", form["stringOrArrayUnion"]); + Assert.Equal("second", form["enumOrBooleanUnion"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"x\",\"count\":1}"), + JObject.Parse((string)form["jsonUnion"]) + )); + Assert.False(form.ContainsKey("nullableUnion")); + Assert.False(form.ContainsKey("optionalUnion")); + Assert.Equal(4, form.Count); + } + + [Fact] + public async Task SendIntegerArrayAndBooleanVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(42), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "a", "b" }), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateBoolean(true), + NullableUnion = FormUnionNullable.CreateInteger(7), + OptionalUnion = FormUnionStringOrInteger.CreateStr("set"), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.Object!.Form!; + + Assert.Equal("42", form["scalarUnion"]); + Assert.Equal( + new List() { "a", "b" }, + form[$"stringOrArrayUnion{FormExplodedArrayKeySuffix}"] + ); + Assert.Equal("true", form["enumOrBooleanUnion"]); + Assert.Equal("7", form["nullableUnion"]); + Assert.Equal("set", form["optionalUnion"]); + Assert.False(form.ContainsKey("jsonUnion")); + Assert.Equal(5, form.Count); + } +} diff --git a/tests/specs/fragments/primary/form-union-fields.yaml b/tests/specs/fragments/primary/form-union-fields.yaml new file mode 100644 index 000000000..756c031e0 --- /dev/null +++ b/tests/specs/fragments/primary/form-union-fields.yaml @@ -0,0 +1,97 @@ +openapi: 3.1.0 +security: + - apiKeyAuth: [] + - oauth2: [] + - clientCredentials: [read, write] + - customSchemeAppId: [] + - basicHttp: [] + - accessToken: [] + - {} +paths: + /anything/formUnionFields: + post: + operationId: requestBodyPostFormUnionFields + tags: + - requestBodies + description: >- + Exercises form-urlencoded request body fields whose schema is a union. + Each field is encoded as if it had been declared with the type of its + active variant: scalar, enum and array variants, a nullable union + holding null, an optional union left unset, and a union with an object + variant encoded as JSON. + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/FormUnionFields" + encoding: + jsonUnion: + contentType: application/json + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + type: object + properties: + form: + type: object + additionalProperties: true +components: + schemas: + FormUnionFields: + type: object + required: + - scalarUnion + properties: + scalarUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayUnion: + $ref: "#/components/schemas/FormUnionStringOrArray" + enumOrBooleanUnion: + $ref: "#/components/schemas/FormUnionEnumOrBoolean" + nullableUnion: + $ref: "#/components/schemas/FormUnionNullable" + optionalUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + jsonUnion: + $ref: "#/components/schemas/FormUnionObjectOrString" + FormUnionStringOrInteger: + oneOf: + - type: string + - type: integer + FormUnionStringOrArray: + oneOf: + - type: string + - type: array + items: + type: string + FormUnionEnumOrBoolean: + oneOf: + - $ref: "#/components/schemas/FormUnionEnum" + - type: boolean + FormUnionNullable: + oneOf: + - type: string + - type: integer + - type: "null" + FormUnionObjectOrString: + oneOf: + - $ref: "#/components/schemas/FormUnionObject" + - type: string + FormUnionEnum: + type: string + enum: + - first + - second + FormUnionObject: + type: object + required: + - label + properties: + label: + type: string + count: + type: integer diff --git a/zSDKs/sdk-csharp/.speakeasy/gen.lock b/zSDKs/sdk-csharp/.speakeasy/gen.lock index 1e437e959..a9a00c42d 100644 --- a/zSDKs/sdk-csharp/.speakeasy/gen.lock +++ b/zSDKs/sdk-csharp/.speakeasy/gen.lock @@ -1484,7 +1484,7 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/OptionalNullableJsonConverter.cs: last_write_checksum: sha1:bf8eec6e762302070ff3a32d58ebc04347c8ed79 src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs: - last_write_checksum: sha1:4f68b905a9c9caee72cafe309fb8f991b9e18a7b + last_write_checksum: sha1:40220d8621930cbe50661c32971d103a8aaa2253 src/Speakeasy/OpenAPI/Utils/ResponseBodyDeserializer.cs: last_write_checksum: sha1:d466d0e2124070f8010d396be9fa10dd9a7fb9d0 src/Speakeasy/OpenAPI/Utils/Retries/BackoffStrategy.cs: @@ -1512,9 +1512,9 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/URLBuilder.cs: last_write_checksum: sha1:27aa6dd3713a24f20a7737dfb966c3c673529cb5 src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs: - last_write_checksum: sha1:9ddf50cc9aee44e22210ad6a12b6001f997487b7 + last_write_checksum: sha1:f50ceb5bd0e472ad8cbd5192adde954d4f4dbf26 src/Speakeasy/OpenAPI/Utils/Utilities.cs: - last_write_checksum: sha1:868a41b840b16955fb0530f8220cf2be15f72967 + last_write_checksum: sha1:c3fd047198f06c29d58dc4f569f5b3f65839550b examples: _operation_with_leading_and_trailing_underscores_: "": diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs index fd629a3de..cde300a8e 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs @@ -353,7 +353,15 @@ private static void SerializeFormValue( ref Dictionary> form ) { - if (Utilities.IsClass(value)) + if (Utilities.IsUnionWrapper(value.GetType())) + { + var variant = GetUnionVariantValue(value); + if (variant != null) + { + SerializeFormValue(fieldName, explode, variant, ref form); + } + } + else if (Utilities.IsClass(value)) { if (Utilities.IsDate(value)) { @@ -513,6 +521,26 @@ ref Dictionary> form } } + private static object? GetUnionVariantValue(object union) + { + foreach (var prop in union.GetType().GetProperties()) + { + var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); + if (metadata == null || metadata.Name != "") + { + continue; + } + + var val = Utilities.UnwrapValue(prop.GetValue(union)); + if (val != null) + { + return val; + } + } + + return null; + } + private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject) { byte[]? content = null; diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs index 59112fe0e..0acc32f3a 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs @@ -151,7 +151,7 @@ JsonSerializerSettings settings private static bool PreCheck(JToken json, Type type) { if (json.Type != JTokenType.Object) return true; - if (IsUnionWrapper(type)) return true; + if (Utilities.IsUnionWrapper(type)) return true; var jo = (JObject)json; foreach (var (prop, attr) in EnumerateJsonProperties(type)) @@ -210,7 +210,7 @@ private static void ScoreValue(UnionCandidateScore score, Type type, object? val return; } - if (IsUnionWrapper(type) && value != null) + if (Utilities.IsUnionWrapper(type) && value != null) { var (variantType, variantValue) = FindActiveVariant(type, value); if (variantValue != null) @@ -382,20 +382,10 @@ private static Type UnwrapOptional(Type t) return t; } - // A union wrapper is a class generated by speakeasy that carries the - // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant - // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). - private static bool IsUnionWrapper(Type type) - { - var attr = type.GetCustomAttribute(); - if (attr == null) return false; - return attr.ConverterType != null && attr.ConverterType.DeclaringType == type; - } - // True when the value is an open union wrapper that fell back to its Unknown sentinel private static bool IsUnknownUnionValue(Type type, object? value) { - if (value == null || !IsUnionWrapper(type)) return false; + if (value == null || !Utilities.IsUnionWrapper(type)) return false; return value is IOpenUnion openUnion && openUnion.IsUnknown(); } diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs index 2f9dd2839..d22821cb1 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs @@ -149,6 +149,16 @@ public static bool IsModelNamespace(string ns) public static bool IsOpenEnum(object? o) => o is IOpenEnum; + // A union wrapper is a class generated by speakeasy that carries the + // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant + // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). + public static bool IsUnionWrapper(Type type) + { + var attr = Attribute.GetCustomAttribute(type, typeof(JsonConverterAttribute)) as JsonConverterAttribute; + if (attr == null) return false; + return attr.ConverterType != null && attr.ConverterType.DeclaringType == type; + } + public static bool IsClass(object? o) { if (o == null) From 666eaa1a042128dc53764b155f5cba74acb9aa38 Mon Sep 17 00:00:00 2001 From: 2ynn Date: Mon, 9 Nov 2026 21:55:00 -0500 Subject: [PATCH 2/3] fix(csharp): unwrap unions nested in form and multipart values Union values that were not themselves a form field were still converted with ValueToString, which sent the wrapper's type name: - items of an array whose items are a union - items of a union variant that is an array of unions - union-typed properties of an object variant of a whole-body union - union-typed values of a map variant of a whole-body union - scalar and array union parts in multipart bodies RequestBodySerializer now unwraps union wrappers to their active variant before converting a value to a string, and omits a value whose union has no active variant. Multipart parts encoded as JSON keep the wrapper so its converter still writes the value. Properties of an object variant of a whole-body union that are generated as JSON-encoded were converted with ValueToString as well, sending an object as its type name and a string unquoted. They are now serialized with SerializeJSON, as top-level form fields already are. The fragment adds array-of-union fields, a whole-body union with a map variant and an object variant holding plain and JSON-encoded union properties, and a multipart operation with scalar, array and JSON-encoded union parts. Tests also cover zero and false variants and single-element arrays. --- .changesets/1794266812-8cefc478.yaml | 2 +- .../Utils/RequestBodySerializer.cs.stmpl | 93 ++++++--- .../FormUnionFieldsAdditionalShould.cs | 183 +++++++++++++++++- .../fragments/primary/form-union-fields.yaml | 128 +++++++++++- zSDKs/sdk-csharp/.speakeasy/gen.lock | 2 +- .../OpenAPI/Utils/RequestBodySerializer.cs | 93 ++++++--- 6 files changed, 439 insertions(+), 62 deletions(-) diff --git a/.changesets/1794266812-8cefc478.yaml b/.changesets/1794266812-8cefc478.yaml index ceb426c52..06ce173bd 100644 --- a/.changesets/1794266812-8cefc478.yaml +++ b/.changesets/1794266812-8cefc478.yaml @@ -5,6 +5,6 @@ targets: - csharp type: fix bump: patch -description: send union-typed fields in form-urlencoded request bodies +description: send union-typed fields in form-urlencoded and multipart request bodies author: 2ynn date: "2026-11-09" diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl index ccf56ee28..77dafce9e 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl @@ -207,7 +207,7 @@ namespace {{getScopeNamespace "utils"}} form.Add(requestFieldName, new List()); } - form[requestFieldName].Add(Utilities.ValueToString(item)); + form[requestFieldName].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -303,26 +303,35 @@ namespace {{getScopeNamespace "utils"}} metadata.Name ?? prop.Name ); } - else if (Utilities.IsList(value)) + else { - var values = new List(); - - foreach (var item in (IList)value) + var formValue = UnwrapUnion(value); + if (formValue == null) { - values.Add(Utilities.ValueToString(item)); + continue; } - foreach (var val in values) + if (Utilities.IsList(formValue)) { - formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + var values = new List(); + + foreach (var item in (IList)formValue) + { + values.Add(Utilities.ValueToString(UnwrapUnion(item))); + } + + foreach (var val in values) + { + formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + } + } + else + { + formData.Add( + new StringContent(Utilities.ValueToString(formValue)), + metadata.Name ?? prop.Name + ); } - } - else - { - formData.Add( - new StringContent(Utilities.ValueToString(value)), - metadata.Name ?? prop.Name - ); } } @@ -350,7 +359,7 @@ namespace {{getScopeNamespace "utils"}} { if (Utilities.IsUnionWrapper(value.GetType())) { - var variant = GetUnionVariantValue(value); + var variant = UnwrapUnion(value); if (variant != null) { SerializeFormValue(fieldName, explode, variant, ref form); @@ -375,8 +384,8 @@ namespace {{getScopeNamespace "utils"}} foreach (var prop in props) { - var val = {{ templateGetPropValue "value" }}; - if (val == null) + var propValue = {{ templateGetPropValue "value" }}; + if (propValue == null) { continue; } @@ -387,6 +396,32 @@ namespace {{getScopeNamespace "utils"}} continue; } + if (metadata.Json) + { + var json = Utilities.SerializeJSON(propValue); + if (explode) + { + if (!form.ContainsKey(metadata.Name)) + { + form[metadata.Name] = new List(); + } + + form[metadata.Name].Add(json); + } + else + { + items.Add($"{metadata.Name},{json}"); + } + + continue; + } + + var val = UnwrapUnion(propValue); + if (val == null) + { + continue; + } + if (explode) { if (!form.ContainsKey(metadata.Name)) @@ -398,7 +433,7 @@ namespace {{getScopeNamespace "utils"}} { foreach(var item in (IEnumerable)val) { - form[metadata.Name].Add(Utilities.ValueToString(item)); + form[metadata.Name].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -412,7 +447,7 @@ namespace {{getScopeNamespace "utils"}} { foreach(var item in (IEnumerable)val) { - items.Add($"{metadata.Name},{Utilities.ValueToString(item)}"); + items.Add($"{metadata.Name},{Utilities.ValueToString(UnwrapUnion(item))}"); } } else @@ -454,12 +489,12 @@ namespace {{getScopeNamespace "utils"}} } form[key].Add( - Utilities.ValueToString(((IDictionary)value)[key]) + Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key])) ); } else { - items.Add($"{key},{Utilities.ValueToString(((IDictionary)value)[key])}"); + items.Add($"{key},{Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key]))}"); } } @@ -482,11 +517,11 @@ namespace {{getScopeNamespace "utils"}} { if (explode) { - values.Add(Utilities.ValueToString(item)); + values.Add(Utilities.ValueToString(UnwrapUnion(item))); } else { - items.Add(Utilities.ValueToString(item)); + items.Add(Utilities.ValueToString(UnwrapUnion(item))); } } @@ -516,6 +551,16 @@ namespace {{getScopeNamespace "utils"}} } } + private static object? UnwrapUnion(object? value) + { + while (value != null && Utilities.IsUnionWrapper(value.GetType())) + { + value = GetUnionVariantValue(value); + } + + return value; + } + private static object? GetUnionVariantValue(object union) { foreach (var prop in union.GetType().GetProperties()) diff --git a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs index d534aa729..7970020bf 100644 --- a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs +++ b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs @@ -21,6 +21,12 @@ public async Task SendStringEnumAndJsonVariants() ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), StringOrArrayUnion = FormUnionStringOrArray.CreateStr("solo"), EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateFormUnionEnum(FormUnionEnum.Second), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateStr("x"), + FormUnionStringOrInteger.CreateInteger(3), + }, + StringOrArrayOfUnion = FormUnionStringOrArrayOfUnion.CreateStr("plain"), NullableUnion = FormUnionNullable.CreateNull(), JsonUnion = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() { @@ -30,18 +36,23 @@ public async Task SendStringEnumAndJsonVariants() }); Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); - var form = res.Object!.Form!; + var form = res.FormUnionEcho!.Form!; Assert.Equal("abc", form["scalarUnion"]); Assert.Equal("solo", form["stringOrArrayUnion"]); Assert.Equal("second", form["enumOrBooleanUnion"]); + Assert.Equal( + new List() { "x", "3" }, + form[$"arrayOfUnion{FormExplodedArrayKeySuffix}"] + ); + Assert.Equal("plain", form["stringOrArrayOfUnion"]); Assert.True(JToken.DeepEquals( JObject.Parse("{\"label\":\"x\",\"count\":1}"), JObject.Parse((string)form["jsonUnion"]) )); Assert.False(form.ContainsKey("nullableUnion")); Assert.False(form.ContainsKey("optionalUnion")); - Assert.Equal(4, form.Count); + Assert.Equal(6, form.Count); } [Fact] @@ -54,12 +65,19 @@ public async Task SendIntegerArrayAndBooleanVariants() ScalarUnion = FormUnionStringOrInteger.CreateInteger(42), StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "a", "b" }), EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateBoolean(true), + StringOrArrayOfUnion = FormUnionStringOrArrayOfUnion.CreateArrayOfFormUnionIntegerOrBoolean( + new List() + { + FormUnionIntegerOrBoolean.CreateInteger(1), + FormUnionIntegerOrBoolean.CreateBoolean(true), + } + ), NullableUnion = FormUnionNullable.CreateInteger(7), OptionalUnion = FormUnionStringOrInteger.CreateStr("set"), }); Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); - var form = res.Object!.Form!; + var form = res.FormUnionEcho!.Form!; Assert.Equal("42", form["scalarUnion"]); Assert.Equal( @@ -67,9 +85,166 @@ public async Task SendIntegerArrayAndBooleanVariants() form[$"stringOrArrayUnion{FormExplodedArrayKeySuffix}"] ); Assert.Equal("true", form["enumOrBooleanUnion"]); + Assert.Equal( + new List() { "1", "true" }, + form[$"stringOrArrayOfUnion{FormExplodedArrayKeySuffix}"] + ); Assert.Equal("7", form["nullableUnion"]); Assert.Equal("set", form["optionalUnion"]); Assert.False(form.ContainsKey("jsonUnion")); - Assert.Equal(5, form.Count); + Assert.Equal(6, form.Count); + } + + [Fact] + public async Task SendDefaultValuesAndSingleElementArrays() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(0), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "only" }), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateBoolean(false), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateInteger(0), + }, + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("0", form["scalarUnion"]); + Assert.Equal("only", form["stringOrArrayUnion"]); + Assert.Equal("false", form["enumOrBooleanUnion"]); + Assert.Equal("0", form["arrayOfUnion"]); + Assert.Equal(4, form.Count); + } + + [Fact] + public async Task SendUnionPropertyOfWholeBodyUnionVariant() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateFormUnionBodyLabeled(new FormUnionBodyLabeled() + { + Label = "x", + LabelValue = FormUnionStringOrInteger.CreateInteger(5), + LabelJson = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "y", + Count = 2, + }), + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("x", form["label"]); + Assert.Equal("5", form["labelValue"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"y\",\"count\":2}"), + JObject.Parse((string)form["labelJson"]) + )); + Assert.Equal(3, form.Count); + } + + [Fact] + public async Task SendJsonStringVariantOfWholeBodyUnionProperty() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateFormUnionBodyLabeled(new FormUnionBodyLabeled() + { + Label = "x", + LabelValue = FormUnionStringOrInteger.CreateStr("v"), + LabelJson = FormUnionObjectOrString.CreateStr("s"), + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("v", form["labelValue"]); + Assert.Equal("\"s\"", form["labelJson"]); + Assert.Equal(3, form.Count); + } + + [Fact] + public async Task SendUnionValuesOfWholeBodyMapVariant() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateMapOfFormUnionStringOrInteger(new Dictionary() + { + { "first", FormUnionStringOrInteger.CreateStr("x") }, + { "second", FormUnionStringOrInteger.CreateInteger(2) }, + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("x", form["first"]); + Assert.Equal("2", form["second"]); + Assert.Equal(2, form.Count); + } + + [Fact] + public async Task SendMultipartUnionParts() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostMultipartUnionFieldsAsync(new MultipartUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "a", "b" }), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateStr("x"), + FormUnionStringOrInteger.CreateInteger(2), + }, + NullableUnion = FormUnionNullable.CreateNull(), + JsonUnion = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "z", + }), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("abc", form["scalarUnion"]); + Assert.Equal(new List() { "a", "b" }, form["stringOrArrayUnion"]); + Assert.Equal(new List() { "x", "2" }, form["arrayOfUnion"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"z\"}"), + JObject.Parse((string)form["jsonUnion"]) + )); + Assert.False(form.ContainsKey("nullableUnion")); + Assert.Equal(4, form.Count); + } + + [Fact] + public async Task SendMultipartIntegerVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostMultipartUnionFieldsAsync(new MultipartUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(0), + NullableUnion = FormUnionNullable.CreateInteger(0), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("0", form["scalarUnion"]); + Assert.Equal("0", form["nullableUnion"]); + Assert.Equal(2, form.Count); } } diff --git a/tests/specs/fragments/primary/form-union-fields.yaml b/tests/specs/fragments/primary/form-union-fields.yaml index 756c031e0..0dc516bf3 100644 --- a/tests/specs/fragments/primary/form-union-fields.yaml +++ b/tests/specs/fragments/primary/form-union-fields.yaml @@ -16,9 +16,10 @@ paths: description: >- Exercises form-urlencoded request body fields whose schema is a union. Each field is encoded as if it had been declared with the type of its - active variant: scalar, enum and array variants, a nullable union - holding null, an optional union left unset, and a union with an object - variant encoded as JSON. + active variant: scalar, enum and array variants, an array of unions, a + union whose array variant holds unions, a nullable union holding null, + an optional union left unset, and a union with an object variant + encoded as JSON. requestBody: required: true content: @@ -34,13 +35,63 @@ paths: content: application/json: schema: - type: object - properties: - form: - type: object - additionalProperties: true + $ref: "#/components/schemas/FormUnionEcho" + /anything/formUnionBody: + post: + operationId: requestBodyPostFormUnionBody + tags: + - requestBodies + description: >- + Exercises a form-urlencoded request body whose schema is a union of + objects and a map. A union-typed property of the active object variant + is encoded as its active variant, or as JSON when the union has an + object variant. Union-typed values of the active map variant are + encoded as their active variant. + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/FormUnionBody" + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + $ref: "#/components/schemas/FormUnionEcho" + /anything/multipartUnionFields: + post: + operationId: requestBodyPostMultipartUnionFields + tags: + - requestBodies + description: >- + Exercises multipart request body parts whose schema is a union. Each + part is encoded as its active variant: a scalar variant, an array + variant sent as repeated parts, and an array of unions sent as + repeated parts. A union with an object variant is encoded as JSON. A + nullable union holding null is omitted. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/MultipartUnionFields" + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + $ref: "#/components/schemas/FormUnionEcho" components: schemas: + FormUnionEcho: + type: object + properties: + form: + type: object + additionalProperties: true FormUnionFields: type: object required: @@ -52,6 +103,12 @@ components: $ref: "#/components/schemas/FormUnionStringOrArray" enumOrBooleanUnion: $ref: "#/components/schemas/FormUnionEnumOrBoolean" + arrayOfUnion: + type: array + items: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayOfUnion: + $ref: "#/components/schemas/FormUnionStringOrArrayOfUnion" nullableUnion: $ref: "#/components/schemas/FormUnionNullable" optionalUnion: @@ -68,6 +125,61 @@ components: - type: array items: type: string + FormUnionStringOrArrayOfUnion: + oneOf: + - type: string + - type: array + items: + $ref: "#/components/schemas/FormUnionIntegerOrBoolean" + FormUnionIntegerOrBoolean: + oneOf: + - type: integer + - type: boolean + FormUnionBody: + oneOf: + - $ref: "#/components/schemas/FormUnionBodyLabeled" + - $ref: "#/components/schemas/FormUnionBodyCounted" + - $ref: "#/components/schemas/FormUnionBodyMap" + FormUnionBodyLabeled: + type: object + required: + - label + - labelValue + properties: + label: + type: string + labelValue: + $ref: "#/components/schemas/FormUnionStringOrInteger" + labelJson: + $ref: "#/components/schemas/FormUnionObjectOrString" + FormUnionBodyCounted: + type: object + required: + - count + properties: + count: + type: integer + FormUnionBodyMap: + type: object + additionalProperties: + $ref: "#/components/schemas/FormUnionStringOrInteger" + MultipartUnionFields: + type: object + required: + - scalarUnion + properties: + scalarUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayUnion: + $ref: "#/components/schemas/FormUnionStringOrArray" + arrayOfUnion: + type: array + items: + $ref: "#/components/schemas/FormUnionStringOrInteger" + nullableUnion: + $ref: "#/components/schemas/FormUnionNullable" + jsonUnion: + $ref: "#/components/schemas/FormUnionObjectOrString" FormUnionEnumOrBoolean: oneOf: - $ref: "#/components/schemas/FormUnionEnum" diff --git a/zSDKs/sdk-csharp/.speakeasy/gen.lock b/zSDKs/sdk-csharp/.speakeasy/gen.lock index a9a00c42d..08e328630 100644 --- a/zSDKs/sdk-csharp/.speakeasy/gen.lock +++ b/zSDKs/sdk-csharp/.speakeasy/gen.lock @@ -1484,7 +1484,7 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/OptionalNullableJsonConverter.cs: last_write_checksum: sha1:bf8eec6e762302070ff3a32d58ebc04347c8ed79 src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs: - last_write_checksum: sha1:40220d8621930cbe50661c32971d103a8aaa2253 + last_write_checksum: sha1:52a1e4363675bb75f23e50a8e9309ddd82e4f717 src/Speakeasy/OpenAPI/Utils/ResponseBodyDeserializer.cs: last_write_checksum: sha1:d466d0e2124070f8010d396be9fa10dd9a7fb9d0 src/Speakeasy/OpenAPI/Utils/Retries/BackoffStrategy.cs: diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs index cde300a8e..0920417e5 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs @@ -212,7 +212,7 @@ ref form form.Add(requestFieldName, new List()); } - form[requestFieldName].Add(Utilities.ValueToString(item)); + form[requestFieldName].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -308,26 +308,35 @@ private static HttpContent SerializeMultipart(object request, string mediaType) metadata.Name ?? prop.Name ); } - else if (Utilities.IsList(value)) + else { - var values = new List(); - - foreach (var item in (IList)value) + var formValue = UnwrapUnion(value); + if (formValue == null) { - values.Add(Utilities.ValueToString(item)); + continue; } - foreach (var val in values) + if (Utilities.IsList(formValue)) { - formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + var values = new List(); + + foreach (var item in (IList)formValue) + { + values.Add(Utilities.ValueToString(UnwrapUnion(item))); + } + + foreach (var val in values) + { + formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + } + } + else + { + formData.Add( + new StringContent(Utilities.ValueToString(formValue)), + metadata.Name ?? prop.Name + ); } - } - else - { - formData.Add( - new StringContent(Utilities.ValueToString(value)), - metadata.Name ?? prop.Name - ); } } @@ -355,7 +364,7 @@ ref Dictionary> form { if (Utilities.IsUnionWrapper(value.GetType())) { - var variant = GetUnionVariantValue(value); + var variant = UnwrapUnion(value); if (variant != null) { SerializeFormValue(fieldName, explode, variant, ref form); @@ -380,8 +389,8 @@ ref Dictionary> form foreach (var prop in props) { - var val = Utilities.UnwrapValue(prop.GetValue(value)); - if (val == null) + var propValue = Utilities.UnwrapValue(prop.GetValue(value)); + if (propValue == null) { continue; } @@ -392,6 +401,32 @@ ref Dictionary> form continue; } + if (metadata.Json) + { + var json = Utilities.SerializeJSON(propValue); + if (explode) + { + if (!form.ContainsKey(metadata.Name)) + { + form[metadata.Name] = new List(); + } + + form[metadata.Name].Add(json); + } + else + { + items.Add($"{metadata.Name},{json}"); + } + + continue; + } + + var val = UnwrapUnion(propValue); + if (val == null) + { + continue; + } + if (explode) { if (!form.ContainsKey(metadata.Name)) @@ -403,7 +438,7 @@ ref Dictionary> form { foreach (var item in (IEnumerable)val) { - form[metadata.Name].Add(Utilities.ValueToString(item)); + form[metadata.Name].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -417,7 +452,7 @@ ref Dictionary> form { foreach (var item in (IEnumerable)val) { - items.Add($"{metadata.Name},{Utilities.ValueToString(item)}"); + items.Add($"{metadata.Name},{Utilities.ValueToString(UnwrapUnion(item))}"); } } else @@ -459,12 +494,12 @@ ref Dictionary> form } form[key].Add( - Utilities.ValueToString(((IDictionary)value)[key]) + Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key])) ); } else { - items.Add($"{key},{Utilities.ValueToString(((IDictionary)value)[key])}"); + items.Add($"{key},{Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key]))}"); } } @@ -487,11 +522,11 @@ ref Dictionary> form { if (explode) { - values.Add(Utilities.ValueToString(item)); + values.Add(Utilities.ValueToString(UnwrapUnion(item))); } else { - items.Add(Utilities.ValueToString(item)); + items.Add(Utilities.ValueToString(UnwrapUnion(item))); } } @@ -521,6 +556,16 @@ ref Dictionary> form } } + private static object? UnwrapUnion(object? value) + { + while (value != null && Utilities.IsUnionWrapper(value.GetType())) + { + value = GetUnionVariantValue(value); + } + + return value; + } + private static object? GetUnionVariantValue(object union) { foreach (var prop in union.GetType().GetProperties()) From 340d655c644b853ca468d73068285cecd4e70741 Mon Sep 17 00:00:00 2001 From: 2ynn Date: Tue, 24 Nov 2026 19:12:54 +0100 Subject: [PATCH 3/3] fix(csharp): send unknown primitive values of open unions in form bodies An open union holding an unknown primitive value is sent as that value instead of being omitted. Union values of a dictionary form body are unwrapped to their active variant. --- .../Utils/RequestBodySerializer.cs.stmpl | 19 +++++++-- .../FormUnionFieldsAdditionalShould.cs | 42 +++++++++++++++++++ .../fragments/primary/form-union-fields.yaml | 12 +++++- zSDKs/sdk-csharp/.speakeasy/gen.lock | 2 +- .../OpenAPI/Utils/RequestBodySerializer.cs | 19 +++++++-- 5 files changed, 85 insertions(+), 9 deletions(-) diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl index 77dafce9e..b206a5165 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl @@ -7,6 +7,7 @@ namespace {{getScopeNamespace "utils"}} using System.Net.Http; using System.Reflection; using System.Text; + using Newtonsoft.Json.Linq; internal class RequestBodySerializer @@ -195,7 +196,7 @@ namespace {{getScopeNamespace "utils"}} form.Add(key, new List()); } - form[key].Add(Utilities.ValueToString(((IDictionary)request)[key])); + form[key].Add(Utilities.ValueToString(UnwrapUnion(((IDictionary)request)[key]))); } } else if (Utilities.IsList(request)) @@ -563,10 +564,22 @@ namespace {{getScopeNamespace "utils"}} private static object? GetUnionVariantValue(object union) { + object? unknownValue = null; + foreach (var prop in union.GetType().GetProperties()) { var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); - if (metadata == null || metadata.Name != "") + if (metadata == null) + { + if (prop.PropertyType == typeof(JToken) && prop.GetValue(union) is JValue raw) + { + unknownValue = raw.Value; + } + + continue; + } + + if (metadata.Name != "") { continue; } @@ -578,7 +591,7 @@ namespace {{getScopeNamespace "utils"}} } } - return null; + return unknownValue; } private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject) diff --git a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs index 7970020bf..28b75e260 100644 --- a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs +++ b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs @@ -121,6 +121,48 @@ public async Task SendDefaultValuesAndSingleElementArrays() Assert.Equal(4, form.Count); } + [Theory] + [InlineData("\"raw\"", "raw")] + [InlineData("7", "7")] + [InlineData("true", "true")] + public async Task SendPrimitiveUnknownValueOfOpenUnion(string rawJson, string expected) + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + OpenUnion = FormUnionOpenStringOrInteger.CreateUnknown(JToken.Parse(rawJson)), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal(expected, form["openUnion"]); + Assert.Equal(2, form.Count); + } + + [Theory] + [InlineData("{\"label\":\"x\"}")] + [InlineData("[1,2]")] + [InlineData("null")] + public async Task OmitNonPrimitiveUnknownValueOfOpenUnion(string rawJson) + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + OpenUnion = FormUnionOpenStringOrInteger.CreateUnknown(JToken.Parse(rawJson)), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.False(form.ContainsKey("openUnion")); + Assert.Equal(1, form.Count); + } + [Fact] public async Task SendUnionPropertyOfWholeBodyUnionVariant() { diff --git a/tests/specs/fragments/primary/form-union-fields.yaml b/tests/specs/fragments/primary/form-union-fields.yaml index 0dc516bf3..3114b794d 100644 --- a/tests/specs/fragments/primary/form-union-fields.yaml +++ b/tests/specs/fragments/primary/form-union-fields.yaml @@ -18,8 +18,9 @@ paths: Each field is encoded as if it had been declared with the type of its active variant: scalar, enum and array variants, an array of unions, a union whose array variant holds unions, a nullable union holding null, - an optional union left unset, and a union with an object variant - encoded as JSON. + an optional union left unset, a union with an object variant + encoded as JSON, and an open union holding an unknown value, encoded + as the raw value when it is a primitive and omitted otherwise. requestBody: required: true content: @@ -115,10 +116,17 @@ components: $ref: "#/components/schemas/FormUnionStringOrInteger" jsonUnion: $ref: "#/components/schemas/FormUnionObjectOrString" + openUnion: + $ref: "#/components/schemas/FormUnionOpenStringOrInteger" FormUnionStringOrInteger: oneOf: - type: string - type: integer + FormUnionOpenStringOrInteger: + x-speakeasy-unknown-values: allow + oneOf: + - type: string + - type: integer FormUnionStringOrArray: oneOf: - type: string diff --git a/zSDKs/sdk-csharp/.speakeasy/gen.lock b/zSDKs/sdk-csharp/.speakeasy/gen.lock index 08e328630..766db7966 100644 --- a/zSDKs/sdk-csharp/.speakeasy/gen.lock +++ b/zSDKs/sdk-csharp/.speakeasy/gen.lock @@ -1484,7 +1484,7 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/OptionalNullableJsonConverter.cs: last_write_checksum: sha1:bf8eec6e762302070ff3a32d58ebc04347c8ed79 src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs: - last_write_checksum: sha1:52a1e4363675bb75f23e50a8e9309ddd82e4f717 + last_write_checksum: sha1:38292e65b7616271d7581e557885b96dcfd5b5b5 src/Speakeasy/OpenAPI/Utils/ResponseBodyDeserializer.cs: last_write_checksum: sha1:d466d0e2124070f8010d396be9fa10dd9a7fb9d0 src/Speakeasy/OpenAPI/Utils/Retries/BackoffStrategy.cs: diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs index 0920417e5..0f00f3b97 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs @@ -15,6 +15,7 @@ namespace Speakeasy.OpenAPI.Utils using System.Net.Http; using System.Reflection; using System.Text; + using Newtonsoft.Json.Linq; internal class RequestBodySerializer { @@ -200,7 +201,7 @@ ref form form.Add(key, new List()); } - form[key].Add(Utilities.ValueToString(((IDictionary)request)[key])); + form[key].Add(Utilities.ValueToString(UnwrapUnion(((IDictionary)request)[key]))); } } else if (Utilities.IsList(request)) @@ -568,10 +569,22 @@ ref Dictionary> form private static object? GetUnionVariantValue(object union) { + object? unknownValue = null; + foreach (var prop in union.GetType().GetProperties()) { var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); - if (metadata == null || metadata.Name != "") + if (metadata == null) + { + if (prop.PropertyType == typeof(JToken) && prop.GetValue(union) is JValue raw) + { + unknownValue = raw.Value; + } + + continue; + } + + if (metadata.Name != "") { continue; } @@ -583,7 +596,7 @@ ref Dictionary> form } } - return null; + return unknownValue; } private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject)