[C#] csharp client support for 'string/binary'
Created by: grmcdorman
Description
When generating code from a spec that has format: binary
and type: string
using the csharp client, the generated code builds an interface with System.IO.Stream
but this usage pattern is not supported by restsharp, including the latest version.
openapi-generator version
Main branch.
OpenAPI declaration file content or url
Partial content:
"paths": {
"/op": {
"parameters": [
{
"name": "data",
"in": "body",
"description": "Binary body data",
"required": true,
"schema": {
"type": "string",
"format": "binary"
}
}
]
}
}
Command line used for generation
java -jar openapi-generator-cli.jar generate -i swagger.json -l csharp -o ClientAPI -c openapi-generation-parameters.json
Steps to reproduce
Generate client, then either inspect code or try to use it. Trying to run results in an exception of type package_.Client.ApiException: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.
Related issues/PRs
#934 (closed) for cpprest client #1327 for aspdotnetcore server
Suggest a fix/enhancement
Internally, it appears that the type used is file
. This is translated to a ''System.IO.Stream`` type in AbstractCSharpCodegen.java around line 172:
typeMapping.put("file", "System.IO.Stream");
In the generated code, the method contains this code:
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
The localVarPostBody
is eventually passed to PrepareRequest
, which adds it as a parameter:
if (postBody != null) // http body (model or byte[]) parameter
{
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
}
AddParameter
is a method in restsharp object RestRequest
. A type of System.IO.Stream is not supported here; the AddParameter
method attempts to serialize the Stream object itself instead of the stream's contents.
Easiest fix is to not support binary file streams, and translate this specification to a byte array (byte []
), just like a string/byte OpenAPI type. This would require an override in the CSharpClientCodegen.java code.
Actually streaming binary files with restsharp appears to be harder, as a web search only turns up sending byte arrays or files as MIME multi-part (i.e. base64 encoded). Neither apply here if a stream is to be used.
Note that while this would be a breaking change for the generated code, given that the current generated code doesn't work it's pretty unlikely anyone's using it.