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

Blazor WASM调用WebAPI反序列化报错:JSON无法转为System.String

问题原因与修复方案

核心问题

你在前端尝试把控制器返回的JSON对象反序列化为string类型,这必然失败——因为响应内容是{"descriptcion":"Something went wrong"},是一个结构化对象,并非纯字符串。

修复步骤

1. 前端使用正确类型反序列化

直接用ResponseMessage类来解析响应内容,而非string:

if (response.StatusCode == HttpStatusCode.BadRequest)
{
    var error = await response.Content.ReadFromJsonAsync<ResponseMessage>();
    NotificationComponent.Show(Notificacion.NotificacionError("error", $"¡ Error, {error.Descriptcion} !"));
}
// Unauthorized分支做同样修改

2. 修正类名与参数的命名匹配

控制器参数声明为[FromBody] Invoices listInvoices,但你定义的类是listInvoices(首字母小写),命名不匹配会导致请求体反序列化失败,统一为规范的 PascalCase 命名:

// 修正类名
public class ListInvoices
{
    public List<Invoices> Invoices { get; set; }
    public List<ProductoDto> Products { get; set; }
}
// 同步修改控制器参数
public ActionResult SendReports([FromBody] ListInvoices listInvoices)

3. 移除冗余的URL参数

Post请求的内容已经通过请求体传递,URL里的?SendReports={listInvoices属于无效冗余,直接删除:

var response = await Http.PostAsJsonAsync("Invoices/SendReports", listInvoices);

4. 可选:统一JSON序列化大小写规则

若想避免属性大小写差异问题,可在后端配置JSON序列化保留 PascalCase:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null;
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:54:54