Int和Int列表作为Asp.Net WebApi调用的参数

时间:2019-06-04 14:05:23

标签: c# json asp.net-web-api

我正在尝试将此数据作为JSON Post发送到名为Dashboard的Asp.Net WebApi控制器。但是使用这些参数,我得到以下错误。知道如何纠正这个问题吗?

{
    "errors": {
        "chartType": [
            "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[System.Int32]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'chartType', line 2, position 13."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "80000864-0007-fd00-b63f-84710c7967bb"
}

JSON:

{ 
    "ChartType": 1,
    "List": [1,2,3]
}

代码:

public void Dashboard(int chartType, List<int> list)
{
    Console.Write("");
}

1 个答案:

答案 0 :(得分:0)

您可以尝试创建类ViewModel

public class ViewModel
{
    public int ChartType { get; set; }
    public List<int> List { get; set; }
}

然后使用FromBody属性。

public void Dashboard([FromBody]ViewModel model)
{
    Console.Write("");
}