asp.net-core - 来自 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
我们可能做错了什么?
解决方案
我认为问题在于 Swagger 文件中的内容为“application/json”,但您的响应不是 JSON。
您需要告诉 Swagger 文件期待“text/plain”或让您的端点返回 JSON 字符串。
推荐阅读
- ios - 如何允许用户将照片添加到其他人可以使用 Firebase 查看的应用
- html - 居中 html/css 导航栏
- asp.net - Scaffold-DbContext 但无法搜索数据库
- jenkins - Jenkins Job 和 FreestyleJob 的区别
- ios - 如何在 uicollectionview 标题中添加 uicollectionview
- java - 读取 CSV 文件并用 Java 编写 Json 文件
- javascript - Google Drive API Picker v3(2018 年 5 月)窗口消失并给出 .split is not a function 错误
- css - 使用 Z-Index 的图像叠加,但看不到下面的元素
- amazon-web-services - 容错集群队列 - SQS
- oracle - 在更新、插入或删除之前检查触发器中的时间