简体   繁体   English

获得 400(错误请求)

[英]Getting 400 (Bad Request)

I am making a jQuery AJAX POST request to my WCF Service.我正在向我的 WCF 服务发出 jQuery AJAX POST 请求。 In this call I am parsing the complex data to the WCF method, but I am getting a 400 Bad Request error.在此调用中,我将复杂数据解析为 WCF 方法,但出现 400 Bad Request 错误。

I am able to get the expected output from the service when i test the same call from Postman.当我测试来自 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  
  }
});

When we transfer parameters with JSON string, we should add escape strings before the quotation marks.当我们用 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);
            }
        })
})

Therefore, Converting a JSON object to a JSON string is necessary before making a call.因此,在进行调用之前,必须将 JSON object 字符串转换为 JSON 字符串。

var compsiteType={
    "StringValue":"Hello",
    "BoolValue":true
};
    dataType:"json",
    data:JSON.stringify(compsiteType),

Besides, 400 Bad Request error typically indicates that there is something wrong with the format of the request parameter.此外,400 Bad Request 错误通常表示请求参数的格式有问题。
Depending on the below attribute, the service method would accept different types of parameter formats.根据以下属性,服务方法将接受不同类型的参数格式。

[WebInvoke(BodyStyle =WebMessageBodyStyle.Bare,RequestFormat =WebMessageFormat.Json)]
        string  GetDataUsingDataContract(CompositeType composite);

Please refer to the links I ever replied to.请参考我曾经回复过的链接。
Get the object is null using JSON in WCF Service 使用 WCF 服务中的 JSON 获取 object 为 null
Feel free to let me know if the problem still exists.如果问题仍然存在,请随时告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM