当我尝试使用ajax从客户端调用WCF服务时,出现400 Bad Request错误。以下是我的代码,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
任何见解都会非常有用......
答案 0 :(得分:0)
你应该尝试的第一件事是使用fiddler点击URL(这样你也可以发布你的数据),看看你是否得到了同样的错误。
您是否正在提出跨域请求。从示例看起来你不是。你能删除
吗?crossDomain: true,
再次尝试jquery。
还有其他一些选项,例如processdata。建议您使用以下代码,看看它是否有效。
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
答案 1 :(得分:0)
根据ajax api documentation,默认内容类型为'application / x-www-form-urlencoded'。发送JSON时,内容类型应为'application / json; charset = utf-8',但WCF不喜欢这样。我得到了相同的错误消息,当我删除内容类型时,我停止了这个错误。顺便说一句,我注意到你将crossDomain设置为true,另一个question与该选项相关。