2012-07-13 195 views
1

当我尝试使用ajax从客户端调用WCF服务时,出现400错误请求错误。以下是我的代码,wcf服务json 400错误请求

[OperationContract] 
[WebInvoke(Method = "POST", 
BodyStyle = WebMessageBodyStyle.Wrapped, 
ResponseFormat = WebMessageFormat.Json)] 
string[] GetUser(string Id); 

$.ajax({ 
       type: "POST", //GET or POST or PUT or DELETE verb 
       url: "http://localhost:58055/Service1.svc/GetUser", 
       crossDomain: true, 
       data: '{"Id": "3"}', 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", //Expected data format from server 
       processdata: true, //True or False 
       success: function (msg) {//On Successfull service call 
        alert(msg.GetUserResult[0]); 
        console.log("success " + msg); 
       }, 
       error: function (msg) {//On Successfull service call 
        console.log(msg); 
       } 
      }); 

任何见解将是真正的帮助......

回答

0

你应该尝试的第一件事就是打使用招(这样你就可以发布您的数据太)的URL,看看是否你会得到同样的错误。

您是否正在提出跨域请求。从这个例子看来,你不是。你能删除

crossDomain: true, 

线,并再次尝试jQuery。

还有其他一些选项,如processdata。建议您使用以下代码并查看它是否有效。

$.ajax({ 
      type: "POST", 
     // the url to the service - 
     url: "url", 
     // the format that the data should be in when 
     // it is returned 
     contentType: "json", 
      data: '{"Id": "3"}', 
     // the function that executes when the server 
     // responds to this ajax request successfully 
     success: function(data) { 

     // put the JSON response in the employees table 

     } 
0

根据ajax api documentation,默认的内容类型是'application/x-www-form-urlencoded'。发送JSON时,内容类型应该是'application/json; charset = utf-8',除了WCF不喜欢那样。我得到了相同的错误消息,当我删除内容类型时,我停止了这个错误。顺便说一下,我注意到您将crossDomain设置为true,另一个question与该选项相关。

相关问题