【问题标题】:"Can't bind multiple parameter to the request's content." in web api and angularJs“无法将多个参数绑定到请求的内容。”在 web api 和 angularJs 中
【发布时间】:2017-06-22 05:34:50
【问题描述】:

当多个参数传入WebApi时,它会导致异常"Can't bind multiple parameter to the request's content."。对于以下代码有任何解决方案

public class A1
{
   public int id {get;set;}
   public string name {get;set;}
}

public class A2
{
   public int id2 {get;set;}
   public string name2 {get;set;}
}

[Route("Save")]
[HttpPost]
public string Save([FromBody]A1 Emp, [FromBody]List<A2> EmpMarks)
{
}

JS 文件

$http({
    method: "post",
    url: "/api/Employee/Save",
    data: JSON.stringify({
        Emp: $scope.Emp,
        EmpMarks: $scope.EmpMarks
    })
}).then(function (response) {

}, function () {
    alert("Error Occur");
})

【问题讨论】:

    标签: javascript c# angularjs asp.net-mvc asp.net-web-api


    【解决方案1】:
    [Route("Save")]
    [HttpPost]
    public string Save(JObject EmpData)
    {
    dynamic json = EmpData;
    A1 Emp=json.Emp.ToObject<A1>();
    List<A2> EmpMarks=json.ToObject<List<A2>>();
    }
    

    这是另一种选择。它对我有用

    【讨论】:

    • 不要使用动态。它会让你痛苦。
    【解决方案2】:

    出现此问题的原因是您两次声明了 [FromBody] 属性。根据设计,http POST 只有一个正文,[FromBody] 将尝试读取正文中的所有内容并将其解析为您指定的对象。

    要解决此问题,您需要创建一个与附加到请求正文的客户端对象匹配的对象。

    public class RequestModel
    {
        public A1 Emp {get;set;}
        public List<A2> EmpMarks {get;set;}
    }
    

    然后从你的 post 方法中的请求正文中获取它

    [Route("Save")]
    [HttpPost]
    public string Save([FromBody]RequestModel Emps)
    

    【讨论】:

      【解决方案3】:

      您可能希望使用包含您的数据的模型:

      public class A1
      {
          public int id { get; set; }
          public string name { get; set; }
      }
      
      public class A2
      {
          public int id2 { get; set; }
          public string name2 { get; set; }
      }
      
      public class AModel 
      {
          public A1 Emp { get; set; }
          public A2 EmpMarks { get; set; }
      }
      
      
      [Route("Save")]
      [HttpPost]
      public string Save(AModel aData)
      {
          // ... your logic here
      }
      

      【讨论】:

        【解决方案4】:

        如果您想将多个参数传递给 POST 调用,您可以简单地执行以下操作并添加尽可能多的参数以匹配服务。

        var data = new FormData();
        data.append('Emp', $scope.Emp);
        data.append('EmpMarks', $scope.EmpMarks);
        $http.post('/api/Employee/Save', **data**, { 
          withCredentials : false,
          transformRequest : angular.identity,
          headers : {
                    'Content-Type' : undefined
            }
          }).success(function(resp) { });
        

        【讨论】:

          猜你喜欢
          • 2020-04-15
          • 1970-01-01
          • 1970-01-01
          • 2017-11-19
          • 2012-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-22
          相关资源
          最近更新 更多