我正在开始使用 WebAPI,大部分情况下一切进展顺利。我遇到了一个特定功能的问题。这个与另一个不同,因为它的唯一参数是 IEnumerable 类型。
我在 Post() 函数的第一行设置了一个断点,我正在点击该函数,但“值”参数的计数始终为 0。我验证了该参数进入客户端实际上,确实包含一个整数数组。如果我删除 [FromUri] 属性,“values”参数为 NULL 而不是计数 0。
如何让我的整数数组通过我的 WebAPI 函数?
这是 WebAPI 函数:
[System.Web.Mvc.HttpPost]
public void Post([FromUri] IEnumerable<int> values)
{
if (values == null || !values.Any()) return;
int sortorder = 1;
foreach (int photoId in values)
{
_horseRepository.UpdateSortOrder(photoId, sortorder);
sortorder++;
}
}
这是 AJAX 调用(这是使用 jQuery UI 可排序功能):
$(".sortable").sortable({
update: function (event, ui) {
var newArray = $(".sortable").sortable("toArray");
$.ajax({
url: '/api/photo',
type: 'POST',
contentType: 'application/json, charset=utf-8',
async: true,
dataType: 'json',
data: JSON.stringify(newArray),
complete: function (data) { }
});
}
});
最佳答案
contentType: 'application/json, charset=utf-8',
应该变成(内容类型和字符集之间的分隔符是分号,而不是逗号):
contentType: 'application/json; charset=utf-8',
和:
public void Post([FromUri] IEnumerable<int> values)
应该变成(POST 请求中没有 Uri 参数):
public void Post(IEnumerable<int> values)
现在您可以假设 newArray
(此处未显示)是一个整数数组:
newArray = [ 1, 2, 3 ]
关于c# - 将 IEnumerable 参数传递给 WebAPI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14148681/