WebApi后端的ListString前端如何发送
目录
WebApi后端的List前端如何发送?
WebApi作为RESTful的风格已经广为流行,在后端有时我们需要传入List
$.post(url,{'list':data},function(success){...})
或者
$.ajax(type:"post",data:{"list":data},success:function(success){...})
或者
var formData=new FormData();
formData.append("list",data);
$.ajax(type:"post",data:formData,success:function(success){...})
但是以上的三种方式,在后端都无法有效的收到数据。后端的WebApi函数如下
[HttpPost]
public HttpResponseMessage Send([FromBody]List<String> list)
{
if(list==null||list.count<=0)
{
//....
}
else
{
//....
}
}
后端收到的list都是0个,为什么呢?
原因在于,这里收的是Request Payload形式的json数据,所以只要我们在ajax的时候指定合适的content-type即可。新的代码如下
$.ajax({
type: 'POST',
url: "/Api/Conversation/CancelRegister",
contentType: 'application/json; charset=utf-8',//将json数据以request payload的形式发起请求
data: JSON.stringify(chatIdList),
success: function (response) {}
});
这时后端即可收到数据了。
转载请注明出处。