c# webapi 未接收 JS 数组

本文关键字:JS 数组 webapi | 更新日期: 2023-09-27 18:37:17

我有一个测试js函数,应该通过Post方法将数据发布到webapi。

function test() {
    var puffs = [];
    var puffObject = {
        id: "2735943",
        priority: "1"
    };
    puffs.push(puffObject);
    puffs.push(puffObject);
    var dto =
    {
        po: puffs
    };
    $.ajax({
        type: "POST",
        url: "../api/PuffPriority/",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(dto),
        dataType: "json",
        success: function (data, status) {
            if (data) {
                console.log("Welcome");
            } else {
                console.log("No data");
            }
        },
        error: function (error) {
            console.log("Error");
        }
    });
}

在控制器类中,我有

public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}

其中 PuffPriority Model 是

public class PuffPriority
{
    public string id { get; set; }
    public string priority { get; set; }
}

我不知道出了什么问题,值是由JS发送的,但api控制器没有获取它:(请帮忙,我已经浪费了很多时间。

c# webapi 未接收 JS 数组

你的代码中有一个错误。只需更改

url: "../api/PuffPriority/"

url: "../api/Post/"

或将方法名称从"发布"更改为"PuffPriority

"

已更改

public void Post(PuffPriority[] po){ 
//Do something here with po, but po is always empty 
}

[FromBody]List<PuffPriority> po{
//Do something here with po, but po is always empty
}