为什么当我使用下面的ajax调用下面的Post方法时,该参数总是为null?
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "value1","value2",value };
}
这里是通过ajax对Web API方法的调用:
function SearchText() {
$("#txtSearch").autocomplete({
source: function (request,response) {
$.ajax({
type: "POST",contentType: "application/json; charset=utf-8",url: "api/search/",data: "test",dataType: "text",success: function (data) {
response(data.d);
},error: function (result) {
alert("Error");
}
});
}
});
}
解决方法
$.ajax({
url: '/api/search',type: 'POST',contentType: 'application/x-www-form-urlencoded; charset=utf-8',data: '=' + encodeURIComponent(request.term),success: function (data) {
response(data.d);
},error: function (result) {
alert('Error');
}
});
基本上你可以只有一个标量类型的参数,用[FromBody]属性装饰,你的请求需要使用application / x-www-form-urlencoded,POST有效载荷应该是这样的:
=somevalue
注意,与标准协议相反,缺少参数名称。您只发送值。
您可以阅读更多关于Web Api中的模型绑定如何在this article中工作。
但当然这个黑客是一个生病的东西。您应该使用视图模型:
public class MyViewModel
{
public string Value { get; set; }
}
然后摆脱[FromBody]属性:
public IEnumerable<string> Post(MyViewModel model)
{
return new string[] { "value1",model.Value };
}
然后使用JSON请求:
$.ajax({
url: '/api/search',contentType: 'application/json; charset=utf-8',data: JSON.stringify({ value: request.term }),error: function (result) {
alert('Error');
}
});
