网络API:使使用POST AJAX请求对象的数组(Axios公司)

问题描述 投票:0回答:1

我试图将数据传递到Web API的路线,但它没有约束力 - 收到的参数始终是零。

在前端,我有工作的阵列,与此类似:

const jobs = [{Id: 1, Name: 'First'}, {Id: 2, Name: 'Second'}] 

我想通过这个阵列到后端,使用POST请求:

axios.post('jobs/insert', jobs, {
  headers: { 'Content-Type': 'application/json' }
})

这是所得到的原始请求:

POST /api/job/insert HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 51
Accept: application/json
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
DNT: 1
Content-Type: application/json
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,fr;q=0.

[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}] 

在后端方面,我有这样的方法:

[HttpPost]
[Route("insert")]
public IActionResult InsertJob([FromBody] List<dto.Job> jobs)
{
    return this.Ok(new { data = jobs });
}

该方法是正确调用,但乔布斯没有正确绑定 - 它始终是零。

这是dto.Job模型:

namespace Scheduling.Models.DTO
{   
    public class Job
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

我试着用List<dto.Job>dto.Job[]IEnumerable<dto.Job>。我还试图消除[FromBody],或张贴对象{'': jobs}代替阵列(在其他网站上所建议的)。似乎没有任何工作,出于某种原因接收到的数据总是空。

我是不是正确?

c# ajax asp.net-web-api axios
1个回答
1
投票

如果你看一下请求主体,该阵列是不是JSON字符串化

这个

[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}] 

应该

"[{"Id":1,"Name":"First"},{"Id":2,"Name":"Second"}]"

在爱可信的请求,试图发送之前字符串化的对象

axios.post('jobs/insert', JSON.stringify(jobs), {
  headers: { 'Content-Type': 'application/json' }
})
© www.soinside.com 2019 - 2024. All rights reserved.