[英]jQuery Ajax JSONP Post call to WCF Service mostly gets 400 Bad Request
嗯,这里有很多相关内容,但是我似乎无法将JSON对象传递到Web服务对象。 我最接近完成这项工作的是此示例,其中ID与服务中的字符串变量名称匹配,如下所示
var jsonData = { "ID": "hello" };
$.ajax({
url: "http://blah/blah.svc/GetPersonByID",
type: "POST",
dataType: "jsonp", // from the server
contentType: "application/json; charset=utf-8", // to the server
data: jsonData,
success: function (msg) {
alert("success " + msg.Name);
},
error: function (xhr, status, error) {
alert(xhr.status + " " + status + " " + error);
}
});
WCF服务在哪里
[OperationContract]
[Description("Returns a person by ID.")]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Person GetPersonByID(string ID);
public Person GetPersonByID(string ID) {
Person person = new Person {
Name = ID, // "Bob",
FavoriteColor = "Red",
UserID = 1 //int.Parse(ID)
};
return person;
}
这将返回“成功ID = hello”。
为什么它返回ID = hello,而不仅仅是问候?
如果我使用数据:JSON.stringify({“ ID”:“ hello”})失败,并显示400错误请求
如果我尝试任何其他数据类型(例如,int)作为Web服务ID(而不是字符串),则失败。
如果我尝试任何更复杂的数据类型,它将失败。
有什么想法吗??? 谢谢
默认情况下,WCF操作期望的主体样式为“裸露”,这意味着输入必须由自身发送(即,它期望像"hello"
类的东西。在这种情况下,您要将其包装在带有参数的对象中)名称( {"ID":"hello"}
)。
您可以使操作期望包装的输入(通过将BodyStyle
属性的WebInvoke
属性设置为WebMessageBodyStyle.WrappedRequest
(和JSON.stringify您的数据),或更改传递给$ .ajax的参数以仅发送JSON字符串( data: "\\"hello\\""
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.