简体   繁体   中英

Getting 400 (Bad Request)

I am making a jQuery AJAX POST request to my WCF Service. In this call I am parsing the complex data to the WCF method, but I am getting a 400 Bad Request error.

I am able to get the expected output from the service when i test the same call from Postman.

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.

       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.

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.
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
Feel free to let me know if the problem still exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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