将List对象和int传递给Web API [英] Passing List object and int to web api
问题描述
我有一个Web api核心项目,如果我只发送list参数,而不是API接收值,但是如果我发送控制器正在寻找的两个参数,则两个参数都将视为空
I have a web api core project that if I send just the list parameter than the API receives the values, however if I send both parameters that the controller is looking for then both parameters are seen as null
我的控制器:
[HttpPost]
[Route("/jobApi/RunBD")]
public int RunBDReport([FromBody]int month, [FromBody] IEnumerable<ClientModel> clients)
{
billingDetailCycle objBillDetail = new billingDetailCycle();
if (ModelState.IsValid)
{
return objBillDetail.Run(clients.ToList(), month);
}
else
{
return 500;
}
}
ClientModel:
ClientModel:
public class ClientModel
{
public string BlockOfBus { get; set; }
public string ClientId { get; set; }
public string Location { get; set; }
public string SuppressSsn { get; set; }
}
我发送的请求:
{"month":7,
"ClientModel":[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]}
这会使控制器将两个参数都视为null,但是如果我这样发送请求:
This causes both parameters to be seen as null by the controller, however if I send my request like this:
[{"blockOfBus":"XXX",
"clientId":"123456",
"location":"",
"suppressSsn":"N"}]
然后,控制器能够看到我正在发送的列表对象(但是由于模型无效,它显然会返回500)
Then the controller is able to see the list object I am sending (however it obviously returns 500 as the model is not valid)
推荐答案
[FromBody]
只能使用一次,因为请求正文只能被读取一次.
[FromBody]
can only be used once since the request body can only be read once.
对于每种操作方法,请勿将
[FromBody]
应用于多个参数.输入格式化程序读取请求流后,将不再可以再次读取该流以绑定其他[FromBody]
参数.
Don't apply
[FromBody]
to more than one parameter per action method. Once the request stream is read by an input formatter, it's no longer available to be read again for binding other[FromBody]
parameters.
创建一个与预期数据匹配的模型.
Create a single model that matches the expected data.
public class DbReport {
public int month { get; set; }
public ClientModel[] ClientModel { get; set; }
}
并相应地更新操作
[HttpPost]
[Route("/jobApi/RunBD")]
public int RunBDReport([FromBody]DbReport report) {
billingDetailCycle objBillDetail = new billingDetailCycle();
if (ModelState.IsValid) {
return objBillDetail.Run(report.ClientModel.ToList(), report.month);
} else {
return 500;
}
}
这篇关于将List对象和int传递给Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!