【问题标题】:WASM Swagger Could not deserialize the response bodyWASM Swagger 无法反序列化响应正文
【发布时间】:2021-12-22 02:38:29
【问题描述】:

我有一个 .net5 WASM 项目和单独的 API。

我使用 API Swagger Endpoint 和 VS2019“向导”在 WASM 中创建了“连接服务”。一切都完美编码。

调用第一个端点时,检索要在 WASM 中显示的数据时出现错误

System.InvalidCastException:从“System.String”到“Sherpr.OpsCalendar.WASM.SherprAPIService.CalendarViewModel”的无效转换

当我查看来自 Fiddler 中 API 的数据时,一切看起来都很好。

当我调试从 swagger 定义生成的代码时,它会遇到以下行:

var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

我可以在 response_.Content _data 中看到 111,032 字节的数据

但是 responseData 返回一个空值,我相信这会导致反序列化问题。

我无法确定生成的代码是错误还是其他问题。

请问有人能解释一下吗?

这里是连接服务向导生成的完整代码...

if (status_ == "200") 
{
   var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); 
   var result_ = default(CalendarViewModel); 
   try
   {
          result_ = (CalendarViewModel)System.Convert.ChangeType(responseData_, typeof(CalendarViewModel));
          return result_; 
   } 
   catch (System.Exception exception_) 
   {
          throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
   }
}

编辑:

经过进一步测试...

jsonContent = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

这行得通:

CalendarViewModel calendarViewModel1 = Newtonsoft.Json.JsonConvert.DeserializeObject<CalendarViewModel>(jsonContent);

这会引发从“System.String”到“Sherpr.OpsCalendar.WASM.SherprAPIService.CalendarViewModel”的无效转换:

CalendarViewModel calendarViewModel2 = (CalendarViewModel)System.Convert.ChangeType(jsonContent, typeof(CalendarViewModel));

【问题讨论】:

  • 问题是(很可能)因为你在某处投射responseData_,你需要反序列化你之前ReadAsStringAsync() 的内容
  • @MindSwipe 我没有写这段代码。它是由“连接服务”VS2019 向导生成的......如果我手动更改它,那么下次我更新“定义”时它将被覆盖:(

标签: c# swagger


【解决方案1】:

原来这是 NSwag 版本 13.2.0.0 中的一个错误

https://github.com/RicoSuter/NSwag/issues/2596

临时修复是添加

[Produces("application/json")]

到您的 API 控制器

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多