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

Blazor中JS向C#传Highcharts系列数据遇循环结构JSON转换错误

Blazor JSInterop 传递Highstock Series数据时循环引用错误解决

问题

尝试通过dotNetHelper将Highstock图表的所有series数据从JavaScript传递到C#,执行window.dotNetHelper.invokeMethodAsync('Items', allSeries)时触发循环引用转JSON失败的错误,无法进入C#的Items方法。

错误信息

blazor.webassembly.js:1 Uncaught (in promise) TypeError: Converting circular structure to JSON
--> starting at object with constructor 'u'
|     property 'alignedObjects' -> object with constructor 'Array'
|     index 0 -> object with constructor 'z'
--- property 'renderer' closes the circle
at JSON.stringify (<anonymous>)
at k (blazor.webassembly.js:1:5176)
at b (blazor.webassembly.js:1:1989)
at A.invokeMethodAsync (blazor.webassembly.js:1:3866)
at v.itemEvent (JSInterop.min.js:269:23)
at highstock.js:17:483
at Array.forEach (<anonymous>)
at f (highstock.js:17:461)
at v.firePointEvent (highstock.js:270:1)
at C.runPointActions (highstock.js:307:340)

现有代码

JavaScript (jsinterop.js)

function itemEvent() {     
    const allSeries = this.series.chart.series;
    //const convert = JSON.parse(JSON.stringify(allSeries))
    window.dotNetHelper.invokeMethodAsync('Items', allSeries); // Error in this line
}

C# (ATComponent.cs)

[JSInvokable]
public void Items(List<Items> allseries)
{
    Console.WriteLine("Enter");// does not enter here
    foreach (var eachItem in allseries)
    {
        Console.WriteLine("eachItem {0}", eachItem);
    }
}

解决方案

错误根源是Highstock的series对象包含循环引用(比如renderer属性引用回上层对象),而Blazor JSInterop在传递数据时会用JSON序列化,无法处理循环引用。解决思路是提取需要的纯数据字段,生成无循环引用的简单对象再传递:

1. 修改JavaScript代码,提取必要数据

不要直接传递整个series对象,而是映射出需要的字段(比如名称、数据点、ID等):

function itemEvent() {     
    // 提取series中的核心数据,避免循环引用
    const simplifiedSeries = this.series.chart.series.map(series => ({
        name: series.name,
        // 只保留数据点的x/y值,按需添加其他字段
        data: series.data.map(point => ({ x: point.x, y: point.y })),
        id: series.id
    }));
    window.dotNetHelper.invokeMethodAsync('Items', simplifiedSeries);
}

2. 调整C#数据模型与JS字段匹配

确保C#的Items类和子属性与JS传递的字段对应(注意大小写,Blazor默认支持驼峰匹配,或可通过JsonPropertyName显式指定):

public class Items
{
    public string Name { get; set; }
    public List<PointData> Data { get; set; }
    public string Id { get; set; }
}

public class PointData
{
    public double X { get; set; }
    public double Y { get; set; }
}

3. 验证C#方法

原Items方法无需修改,只要数据模型匹配,即可正常接收并处理数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:27:44