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

Asp.Net Core MVC中JsonSerializer.Serialize报错,需安装什么NuGet包?

问题解答:JsonSerializer 缺失重载及红色波浪线解决方法

所需NuGet包

你需要安装**System.Text.Json**这个NuGet包。JsonSerializer类属于System.Text.Json命名空间,Asp.Net Core项目部分模板会默认引入该依赖,但如果出现方法重载缺失、代码下出现红色波浪线的情况,手动安装该包即可解决。

安装方式:在Visual Studio的NuGet包管理器中搜索System.Text.Json并安装,或者通过Package Manager控制台执行命令:

Install-Package System.Text.Json

代码逻辑修正提示

你的代码存在一处逻辑错误,会导致Index2方法无法正确获取数据:
在Index方法中,你未将序列化后的data存入TempData["products"],而是存入了TempData["x"],这会导致Index2里TempData["products"]为null,调用ToString()时抛出空引用异常。修正后的Index方法关键代码如下:

public IActionResult Index()
{
    var products = new List<Product>
    {
        new Product{Id = 1, ProductName= "Kulaklik", Quantity = 4},
        new Product{Id = 2, ProductName= "Şarj Kablosu", Quantity = 6},
        new Product{Id = 3, ProductName= "Akilli Saat", Quantity = 5}
    };
    
    string data = JsonSerializer.Serialize(products);
    // 将序列化后的数据存入TempData["products"]
    TempData["products"] = data;

    return RedirectToAction("Index2");
}

另外,为避免空引用问题,Index2方法建议先判断数据是否为空:

public IActionResult Index2()
{
    var data = TempData["products"]?.ToString();
    if (string.IsNullOrEmpty(data))
    {
        // 处理数据为空的情况,比如返回空列表视图
        return View(new List<Product>());
    }
    List<Product> products = JsonSerializer.Deserialize<List<Product>>(data);

    return View(products);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:50:25