首页 > 解决方案 > 来自 NSwag CSharpClientGenerator 的客户端无法反序列化字符串

问题描述

通过使用 AddOpenApiDocument(见下文),我们有一个 Swagger.json 输出。

如下所示的 swagger 片段显示它返回 200 响应类型的 application/json。模式部分(我不太熟悉)显示“类型”:“字符串”。

当我们从 NSwag.CodeGeneration.CSharp.CSharpClientGenerator 生成和使用客户端时,我们会收到以下错误:

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.

大摇大摆的片段

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

生成的客户端代码如下所示:

                    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);
                    }

提琴手的捕获是:

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

我们可能做错了什么?

标签: asp.net-coreswaggeropenapiopenapi-generatornswag

解决方案


我认为问题在于 Swagger 文件中的内容为“application/json”,但您的响应不是 JSON。

您需要告诉 Swagger 文件期待“text/plain”或让您的端点返回 JSON 字符串。


推荐阅读