首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Webapi接收带括号的json

Webapi接收带括号的json
EN

Stack Overflow用户
提问于 2019-03-18 01:15:35
回答 1查看 67关注 0票数 1

我只是想理解,我花了几天的时间试图解决POST操作不起作用的问题(使用Web Api和Angular JS)。我考虑了所有的事情,尝试,搜索,我甚至修改了代码一千次。在那之后,我发现当JSON格式是这样的时候,POST是工作的:

{"Name":"Test","Age":23}

但是如果我使用JSON.stringify(options.models);

POST操作不起作用,其格式如下:

[{"Name":"Test","Age":23}]

我不明白它们之间有什么不同(不管括号[])

为什么第一个有效,而第二个不起作用?

有没有办法让第二种格式起作用?

第二个是JSON数组吗?

JSON.stringify(options.models)不应该返回JSON格式吗?

类:

 public class EmployeesData
        {
            public EmployeesData() { }
            public EmployeesData(int Id, string Name, int Age, int Phone,string Job, string Department)
            {   this.ID = Id;
                this.Name = Name;
                this.Age = Age;
                this.Phone = Phone;
                this.Job = Job;
                this.Department = Department;}

            [Required]
            public int ID { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }

        }

在WebApi中:

    [HttpPost]
        [ResponseType(typeof(EmployeesData))]

        public async Task<IHttpActionResult> Post([FromBody]EmployeesData employeesData) 
{
            if (!ModelState.IsValid) {
              return BadRequest(ModelState);}

            db.Employees.Add(employeesData);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = employeesData.ID }, employeesData);
        }

在Angularjs中:

parameterMap: function(options, operation) {
        if (operation !== "read") {
             console.log(kendo.stringify(options));
              console.log(JSON.stringify(options.models)); // Not work because of []
             var R = JSON.stringify(options.models).replace(/]|[[]/g, ''); // work I removed []
                                console.log(operation + R);

                             return (R);
                            }


                        }
                    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-18 01:30:32

提到的两种格式({"Name":"Test","Age":23}[{"Name":"Test","Age":23}])都表示两种不同的合同。

第一个只是一个对象,第二个是对象集合。

假设您从angular发送{"Name":"Test","Age":23},那么您的Api控制器方法应该如下所示

public void Demo(Test test)
{
  ///code here 
}

测试应该在哪里?

public class Test 
{
   public string Name {get;set;}
   public int Age {get;set;}
}

如果你正在发送{"Name":"Test","Age":23},那么你的控制器应该是这样的

public void Demo(ICollection<Test> test)
{
  ///code here 
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55209757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档