[英]Getting 400 (Bad Request)
我正在向我的 WCF 服务发出 jQuery AJAX POST 请求。 在此调用中,我将复杂数据解析为 WCF 方法,但出现 400 Bad Request 错误。
当我测试来自 Postman 的相同调用时,我能够从服务中获得预期的 output。
var data = {
// my data
};
var url = "my service url"
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: "application/json; charset=UTF-8",
crossDomain: "*",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
success: function(resp) {
alert('Success' + resp);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Status: " + jqXHR.status + "; Error: " + jqXHR.responseText); // Display error message
}
});
当我们用 JSON 字符串传递参数时,我们应该在引号前添加转义字符串。
var compsiteType={
"StringValue":"Hello",
"BoolValue":true
};
$(function(){
$.ajax({
method:"POST",
url: "http://10.157.13.69:8864/Service1.svc/GetDataUsingDataContract",
dataType:"json",
data:'{\"StringValue\":\"Hello\",\"BoolValue\":true}',
contentType: "application/json",
complete: function(data){
$("#main").html(data.responseText);
}
})
})
因此,在进行调用之前,必须将 JSON object 字符串转换为 JSON 字符串。
var compsiteType={
"StringValue":"Hello",
"BoolValue":true
};
dataType:"json",
data:JSON.stringify(compsiteType),
此外,400 Bad Request 错误通常表示请求参数的格式有问题。
根据以下属性,服务方法将接受不同类型的参数格式。
[WebInvoke(BodyStyle =WebMessageBodyStyle.Bare,RequestFormat =WebMessageFormat.Json)]
string GetDataUsingDataContract(CompositeType composite);
请参考我曾经回复过的链接。
使用 WCF 服务中的 JSON 获取 object 为 null
如果问题仍然存在,请随时告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.