简体   繁体   English

wcf服务json 400错误请求

[英]wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. 当我尝试使用ajax从客户端调用WCF服务时,出现400错误请求错误。 Following is my code, 以下是我的代码,

[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);
                }
            });

Any insights would be really helpfull... 任何见解都会非常有帮助...

The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error. 您应该尝试的第一件事是使用fiddler击中URL(以便您也可以发布数据),看看是否遇到相同的错误。

Are you making a cross domain request. 您是否在提出跨域请求。 From the example it looks like you are not. 从该示例看来,您似乎不是。 Could you remove 你能删除吗

crossDomain: true,

line and try the jquery again. 行,然后再次尝试使用jquery。

There are other options also which unnecessay like processdata. 还有其他一些不必要的选项,例如过程数据。 Suggest you to use the following code and see if it works or not. 建议您使用以下代码,看看它是否有效。

$.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

        }

According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. 根据ajax api文档 ,默认内容类型为'application / x-www-form-urlencoded'。 When sending JSON, the content type should be 'application/json; 发送JSON时,内容类型应为'application / json; charset=utf-8' except that WCF does not like that. charset = utf-8',只是WCF不喜欢这样。 I got the same error messages and when I removed the content type I stopped getting this error. 我收到了相同的错误消息,删除内容类型后,我停止收到此错误。 By the way, I noticed that you set crossDomain to true, this other question is relevant to that option. 顺便说一句,我注意到您将crossDomain设置为true,这另一个问题与该选项有关。

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

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