【问题标题】:Getting 400 (Bad Request)获得 400(错误请求)
【发布时间】:2020-04-28 07:21:08
【问题描述】:

我正在向我的 WCF 服务发出 jQuery AJAX POST 请求。在此调用中,我将复杂数据解析为 WCF 方法,但收到 400 Bad Request 错误。

当我测试来自 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  
  }
});

【问题讨论】:

  • 您的 JS 代码看起来不错,但我建议删除 content-type 标头并让 jQuery 为您执行此操作。由于您在请求中发送的数据与接收方制定的格式或业务规则不匹配,因此会引发 400 错误。因此,您需要从服务器端进行调试。这是跨域请求吗?
  • 如果真的要发送JSON,需要使用data: JSON.stringify(data),
  • 如果您为data: 选项使用对象,jQuery 将以 URL 编码格式序列化它,而不是 JSON。

标签: jquery ajax wcf post


【解决方案1】:

当我们使用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 对象转换为 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);

请参考我曾经回复过的链接。
Get the object is null using JSON in WCF Service
如果问题仍然存在,请随时告诉我。

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多