我正在尝试使用 ApiController 将复杂对象与非序列列表绑定(bind)在一起。除列表外的所有字段都设置正确,但列表包含一个元素(即使发布了两个列表元素)并且该元素为空。如果我采用完全相同的代码并将其指向在我的操作方法中使用相同参数类型的 MVC Controller ,一切都会按预期进行。
由于我使用的是非序列列表,因此我使用了隐藏的“.Index”输入,如 Phil Haack (http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx) 所述
如果我删除“.Index”输入并将列表作为从 0 开始的顺序列表发送,ApiController 也会正确绑定(bind)列表。(此选项适用于测试,但在生产中不是一个很好的选择,因为列表项可以由用户添加和删除,这就是我要使用非顺序列表的原因。)
我了解 Web API Controller 以不同于 MVC Controller 的方式进行参数绑定(bind),如所讨论的那样 here ,但似乎非顺序列表应该在 Web API Controller 中正确绑定(bind)。我错过了什么吗?为什么相同的代码适用于 MVC Controller 而不适用于 Web API Controller ?如何让非序列列表在 Web API 中正确绑定(bind)?
这是我的帖子参数:
Parameters application/x-www-form-urlencoded
BatchProductLots.Index 1
BatchProductLots.Index 2
BatchProductLots[1].BrandId 1
BatchProductLots[1].ContainerId 9
BatchProductLots[1].ContainerLot 123
BatchProductLots[1].PackageId 2
BatchProductLots[1].PlannedQuantity 0
BatchProductLots[1].ProducedQuantity 20
BatchProductLots[2].BrandId 1
BatchProductLots[2].ContainerId 9
BatchProductLots[2].ContainerLot 123
BatchProductLots[2].PackageId 1
BatchProductLots[2].PlannedQuantity 0
BatchProductLots[2].ProducedQuantity 1
BatchStatusId 1
LotNumber 070313
ProductionDate 07/03/2013
RecipeId 1
RecipeQuantity 1
SauceId 22
X-Requested-With XMLHttpRequest
这是我的 Web API Controller 操作:
(request.BatchProductLots 列表设置为一个元素(即使发布了两个元素)并且该元素为空)
public Response Create(BatchCreateRequest request)
{
Response response = new Response();
try
{
Batch batch = Mapper.Map<Batch>(request);
batchService.Save(batch);
response.Success = true;
}
catch (Exception ex)
{
response.Message = ex.Message;
response.Success = false;
}
return response;
}
这是我尝试绑定(bind)到的带有列表的复杂对象:
public class BatchCreateRequest
{
public int BatchStatusId { get; set; }
public DateTime ProductionDate { get; set; }
public string LotNumber { get; set; }
public int SauceId { get; set; }
public int RecipeId { get; set; }
public int RecipeQuantity { get; set; }
public List<BatchProductLot> BatchProductLots { get; set; }
public class BatchProductLot
{
public int BrandId { get; set; }
public int ContainerId { get; set; }
public string ContainerLot { get; set; }
public int PackageId { get; set; }
public int PlannedQuantity { get; set; }
public int ProducedQuantity { get; set; }
}
}
最佳答案
简而言之,使用 Web Api 的模型绑定(bind)器是不可能的。 MVC 和 Web Api 使用不同的模型绑定(bind)器,而 Web Api 模型绑定(bind)器仅适用于简单类型。
参见 this answer获取进一步解释以及可能解决方案的链接。
更长的答案,创建 System.Web.Http.ModelBinding.IModelBinder 的自定义实现并将您的 Action 签名更改为以下内容
public Response Create([ModelBinder(CustomModelBinder)]BatchCreateRequest request)
关于c# - ASP.NET Web API 模型绑定(bind)复杂对象的非顺序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17576261/