Client From NSwag CSharpClientGenerator Cannot Deserialize String

Viewed 2654

We have a Swagger.json output by using AddOpenApiDocument (see below).

A snippet from the swagger as below shows it returns a 200 response type of application/json. The schema part (which I am not too familiar with) shows "type": "string".

When we generate and use a client from NSwag.CodeGeneration.CSharp.CSharpClientGenerator we get an error of:

SwaggerException: Could not deserialize the response body stream as System.String.
Status: 200
Response: 

 ---> Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: P. 
Path '', line 1, position 1.

swagger snippet

"/api/infrastructure": {
  "get": {
    "tags": [
      "Infrastructure"
    ],
    "operationId": "Infrastructure_Ping",
    "responses": {
      "200": {
        "description": "",
        "content": {
          "application/json": {
            "schema": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

The generate client code looks like this:

                    var status_ = (int)response_.StatusCode;
                    if (status_ == 200)
                    {
                        var objectResponse_ = await ReadObjectResponseAsync<string>(response_, headers_, cancellationToken).ConfigureAwait(false);
                        if (objectResponse_.Object == null)
                        {
                            throw new YadaYada.Library.Client.SwaggerException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
                        }
                        return objectResponse_.Object;
                    }
                    else
                    {
                        var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
                        throw new YadaYada.Library.Client.SwaggerException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
                    }

The capture from fiddler is:

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 41
Connection: keep-alive
Date: Mon, 26 Apr 2021 12:29:10 GMT
Cache-Control: no-store
Apigw-Requestid: eZDDBie8oAMEM7A=
X-Cache: Miss from cloudfront
Via: 1.1 ec8b1bfbf511818c606f196b49f871e2.cloudfront.net (CloudFront)
X-Amz-Cf-Pop: IAD50-C2
X-Amz-Cf-Id: G90aS8nFabyc4j8jdQ8jHlWdD8GhSqwk-vx8G6gHWnyg-9BIfvYE1Q==

Pong3

What might we be doing wrong?

1 Answers

I believe the issue is that in the Swagger file you have a content of "application/json", but your response is not JSON.

You need to either tell the Swagger file to expect "text/plain" or have your endpoint return a JSON string.

Related