【问题标题】:Webapi receive json with bracketsWebapi接收带括号的json
【发布时间】:2019-08-08 03:16:09
【问题描述】:

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

{"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);
                            }


                        }
                    }

【问题讨论】:

  • 你试图调用的WebApi函数的函数原型是什么?
  • 您能否更新问题而不是发表评论。它使代码更易于阅读。另外,您可以发布EmployeesInfo 课程吗,我怀疑这是问题的原因..
  • 我更新了问题,请您检查一下

标签: c# angularjs asp.net-web-api kendo-grid


【解决方案1】:

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

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

假设如果您从 Angular 发送 {"Name":"Test","Age":23},那么您的 Api 控制器方法应该是这样的

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

Test 在哪里

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 
}

【讨论】:

  • 太棒了!在 ICollection 中你能做类似 test.Name 的事情吗?
  • 您不能在集合中执行test.Name,但您可以在集合中的一项上执行此操作。
  • 如果你想在集合中做 test.Name 你应该迭代它。例如:foreach(var item in test) { Console.WriteLine(item.Name); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2016-07-17
  • 2013-09-28
相关资源
最近更新 更多