[BUG][csharp] httpclient: oneOf/anyOf responses throw ArgumentException because FromJson is invoked with HttpContent
Los mantenedores suelen responder en 1 día
Evaluación
- Dificultad
- 2/5
- Tiempo estimado
- 1-3 horas
- Aptitud para principiantes
- 78/100
Línea de trabajo
Comienza en modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache, alrededor del manejo de AbstractOpenAPISchema en ApiClient.ExecAsync. Genera la especificación Pets proporcionada con la biblioteca csharp httpclient y ejecuta la reproducción de la respuesta oneOf. La tarea está completada cuando el cliente generado devuelve la instancia Cat y no se lanza ninguna ArgumentException.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Bug Report Checklist
- Have you provided a full/minimal spec to reproduce the issue?
- Have you validated the input using an OpenAPI validator?
- Have you tested with the latest master to confirm the issue still exists?
- Have you searched for related issues/PRs?
- What's the actual output vs expected output?
- [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description
With the csharp generator and --library=httpclient, any operation whose response schema is a oneOf (or anyOf) throws at runtime, even when the server returns a valid response.
After deserializing a successful response, ApiClient.ExecAsync has a special case for AbstractOpenAPISchema types:
object responseData = await deserializer.Deserialize<T>(response).ConfigureAwait(false);
// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
if (typeof(Pets.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
{
responseData = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
}
FromJson(string jsonString) takes a JSON string, but the code passes response.Content, which is an HttpContent. Because the call goes through reflection it compiles, then fails on every call:
Unhandled exception. System.ArgumentException: Object of type 'System.Net.Http.HttpConnectionResponseContent' cannot be converted to type 'System.String'.
at System.RuntimeType.CheckValue(Object& value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Pets.Client.ApiClient.ExecAsync[T](HttpRequestMessage req, IReadableConfiguration configuration, CancellationToken cancellationToken)
at Pets.Client.ApiClient.Exec[T](HttpRequestMessage req, IReadableConfiguration configuration)
at Pets.Client.ApiClient.Get[T](String path, RequestOptions options, IReadableConfiguration configuration)
at Pets.Api.DefaultApi.GetPetWithHttpInfo()
This makes every operation with a oneOf/anyOf response unusable with the httpclient library.
openapi-generator version
- 7.25.0
- 7.26.0-SNAPSHOT (master,
20261001.032649-175)
Not a recent regression: the same line is in the httpclient ApiClient.mustache at v5.4.0 (csharp-netcore), v6.0.0, v7.0.0, and current master.
OpenAPI declaration file content or url
openapi: 3.0.3
info:
title: Pets
version: '1'
paths:
/pet:
get:
operationId: getPet
responses:
'200':
description: A cat or a dog.
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
components:
schemas:
Cat:
type: object
required: [meows]
properties:
meows:
type: boolean
additionalProperties: false
Dog:
type: object
required: [barks]
properties:
barks:
type: boolean
additionalProperties: false
openapi-generator-cli validate -i pets.yaml reports No validation issues detected.
Generation Details
java -jar openapi-generator-cli.jar generate \
-i pets.yaml \
-g csharp \
--library=httpclient \
-o gen \
--additional-properties=packageName=Pets
The generated client targets net10.0 and was run on .NET runtime 10.0.12.
Steps to reproduce
-
Generate the client with the command above.
-
Serve
GET /petreturning{"meows": true}withContent-Type: application/jsononhttp://127.0.0.1:18803. -
Run a console program that references the generated project:
using System; using Pets.Api; using Pets.Client; public static class Program using Pets.Client; public static class Program { public static void Main() { var api = new DefaultApi(new Configuration { BasePath = "http://127.0.0.1:18803" }); var pet = api.GetPet(); Console.WriteLine("OK: " + pet.ActualInstance.GetType().Name); } }
Expected output: OK: Cat
Actual output: the ArgumentException above, thrown from ApiClient.ExecAsync.
Related issues/PRs
I couldn't find an existing report. I searched issues for httpclient FromJson response.Content, HttpConnectionResponseContent cannot be converted, and csharp httpclient oneOf FromJson.
Suggest a fix
The problem is in modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache (line 566 on master):
responseData = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
Passing the body text fixes it. HttpClient has already buffered the content, so it can be read again:
responseData = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { await response.Content.ReadAsStringAsync().ConfigureAwait(false) });
With this change the reproduction above prints OK: Cat.
Removing the block may also work. The Deserialize<T> call just before it already returns the correct type, because each oneOf/anyOf model has a [JsonConverter(typeof(...JsonConverter))] attribute that Newtonsoft.Json uses.
I only ran oneOf responses. The anyOf claim comes from the code: the branch checks AbstractOpenAPISchema, which both kinds of model inherit from. To keep the issue strictly to what was tested, change "oneOf (or anyOf)" to just "oneOf".
- Lenguaje dominante
- Java
- Estrellas
- 26.8k
- Forks
- 7.7k
- Merge medio
- 1 d 11 h
- PR fusionados (30 d)
- 142
Preparar el entorno
Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.
- Incluye un Dockerfile o un archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de OpenAPITools/openapi-generator
-
[REQ][swift6] Don't pretty-print JSON request bodiesPosiblemente ocupada @spigo la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
OpenAPITools/openapi-generator#25186 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
OpenAPITools/openapi-generator#25154 ·
Los mantenedores suelen responder en 1 día
-
[BUG][Java][Spring] `HttpInterfacesAbstractConfigurator` is not marked `@Generated`Posiblemente ocupada @axelray-dev la tomó hace 4 días. AbiertoIssue: Bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
OpenAPITools/openapi-generator#25121 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
OpenAPITools/openapi-generator#24997 ·
Los mantenedores suelen responder en 1 día
-
[BUG][KOTLIN] Jackson3 option does not discover modules like Jackson2 doesPosiblemente ocupada @kdelay la tomó hace 34 días. AbiertoIssue: Bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
OpenAPITools/openapi-generator#24859 ·
Los mantenedores suelen responder en 1 día
Todos los issues de OpenAPITools/openapi-generator
Issues similares
-
[Bug] AI unread message badge counts a batch of new bubbles as one messagePosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
apache/rocketmq-dashboard#5784 ·
Los mantenedores suelen responder en 3 días
-
[i18n] 安装实例完成后的成功提示未正确本地化Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
PCL-Community/PCL-CE#3658 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 66/100
apache/skywalking#14127 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 1 día
-
Team/Identity Server Core Type/Improvement U2
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
wso2/product-is#28553 ·
Los mantenedores suelen responder en 1 día