使用Post方法将数据从JavaScript发布到ApiController
我通过javascript代码调用webservice,如下所示:使用Post方法将数据从JavaScript发布到ApiController,javascript,asp.net-apicontroller,Javascript,Asp.net Apicontroller,我通过javascript代码调用webservice,如下所示: function callActionAjax(action, data) { //action is "sendnotification" var deferred = jQuery.Deferred(); getWebServiceUrl().done(function (webServiceUrl) { //returns https://server/api var s = {
function callActionAjax(action, data) { //action is "sendnotification"
var deferred = jQuery.Deferred();
getWebServiceUrl().done(function (webServiceUrl) { //returns https://server/api
var s = {
crossDomain: true,
xhrFields: { withCredentials: true },
url: webServiceUrl + "/" + action,
data: "foobar", //also tried: JSON.stringify(data)
type: "POST"
//tried contentType: "application/json"
};
jQuery.ajax(s).done(function () {
deferred.resolve();
}).fail(function () {
deferred.reject();
});
});
return deferred.promise();
}
public class SendNotificationController : ApiController
{
public void PostSendNotification(dynamic data)
{
Console.Write("foo");
}
public string GetSendNotification()
{
return "Foo Bar.";
}
}
我还有MVC服务,它接收请求。我的控制器如下所示:
function callActionAjax(action, data) { //action is "sendnotification"
var deferred = jQuery.Deferred();
getWebServiceUrl().done(function (webServiceUrl) { //returns https://server/api
var s = {
crossDomain: true,
xhrFields: { withCredentials: true },
url: webServiceUrl + "/" + action,
data: "foobar", //also tried: JSON.stringify(data)
type: "POST"
//tried contentType: "application/json"
};
jQuery.ajax(s).done(function () {
deferred.resolve();
}).fail(function () {
deferred.reject();
});
});
return deferred.promise();
}
public class SendNotificationController : ApiController
{
public void PostSendNotification(dynamic data)
{
Console.Write("foo");
}
public string GetSendNotification()
{
return "Foo Bar.";
}
}
我在PostSendNotification中有一个断点。我可以看到,该方法接收到请求,但是数据
只是一个空对象。当我尝试在JS端添加contentType
时,断点不会被命中
如何调整我的代码?最后,我希望在控制器中检索我的数据
,并能够对其进行处理 改变你的想法
type: "POST"
到
cheers尝试将参数类型更改为string,而不是使用dynamic,并在java脚本中将数据“foobar”修改为数据:{data:“foobar”},