You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET5 WASM项目通过Swagger连接服务调用API时遭遇反序列化失败与类型转换异常问题求助

System.InvalidCastException when using VS2019 Connected Service for .NET 5 WASM with Swagger API

这问题的根源其实很清晰——VS2019的Connected Service向导生成的代码用了完全错误的方式处理API返回的JSON数据。System.Convert.ChangeType()根本不是用来反序列化JSON字符串到强类型对象的方法,它只能处理基础类型的转换(比如字符串转int、DateTime这类),完全没法把JSON字符串直接转换成你的CalendarViewModel类实例,这就是为什么你手动用Newtonsoft.Json反序列化能成功,而生成的代码直接报错。

先看生成代码的问题点

这段自动生成的代码是核心错误来源:

result_ = (CalendarViewModel)System.Convert.ChangeType(responseData_, typeof(CalendarViewModel));

这里的responseData_是API返回的JSON字符串,Convert.ChangeType完全不知道如何解析这个字符串并映射到你的自定义ViewModel类上,自然会抛出类型转换异常。

解决方案1:手动修改生成的代码(快速临时修复)

你可以直接修改Connected Service生成的代码,把错误的转换逻辑替换成你已经验证有效的JSON反序列化代码:

if (status_ == "200") {
    var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
    var result_ = default(CalendarViewModel);
    try {
        // 替换为正确的反序列化逻辑
        result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<CalendarViewModel>(responseData_);
        return result_;
    } catch (System.Exception exception_) {
        throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_);
    }
}

⚠️ 注意:如果后续你重新运行Connected Service向导生成代码,这个修改会被覆盖,所以更推荐下面的第二种方法。

解决方案2:调整Connected Service的生成配置(长期解决)

VS2019的Swagger Connected Service向导其实支持配置正确的序列化库,你可以重新添加Connected Service,在配置步骤中:

  • 找到序列化相关的选项,选择使用Newtonsoft.Json(或者你的项目正在使用的System.Text.Json)
  • 确保向导生成的代码会使用对应的反序列化方法,而不是错误的Convert.ChangeType

另外你提到responseData_返回null但response_.Content有数据的问题,大概率是调试时的临时读取异常,当你替换成正确的反序列化逻辑后,这个问题应该会自动消失——毕竟你手动测试时ReadAsStringAsync()是能正常获取到内容的。

如果你的项目使用的是System.Text.Json而非Newtonsoft.Json,只需要把反序列化代码替换为:

result_ = System.Text.Json.JsonSerializer.Deserialize<CalendarViewModel>(responseData_);

内容的提问来源于stack exchange,提问作者Trevor Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:52:47