“Can't bind multiple parameter to the request's content.” in web api and angularJs

孤街浪徒 提交于 2020-01-22 15:05:47

问题


When Multiple parameters pass in WebApi it results as an exception "Can't bind multiple parameter to the request's content.".Have any solution for following code

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 file

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

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

回答1:


You might want to use a model which contains your data:

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
}



回答2:


The issue occours because you are declaring the [FromBody] attribute twice. As per design, http POST does only have one body and the [FromBody] will try to read all content in the body and parse it to your specified object.

To solve this issue you need to create an object which matches your client object which is being attach to the request body.

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

Then fetch that from the request body in your post method

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



回答3:


[Route("Save")]
[HttpPost]
public string Save(JObject EmpData)
{
dynamic json = EmpData;
A1 Emp=json.Emp.ToObject<A1>();
List<A2> EmpMarks=json.ToObject<List<A2>>();
}

It is an another option.It is work for me




回答4:


If you want to pass multiple parameters to a POST call, you can simply do as below and add as many to match the service.

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


来源:https://stackoverflow.com/questions/44690905/cant-bind-multiple-parameter-to-the-requests-content-in-web-api-and-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!