[英]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.