0

I am trying to use CORS on WCF for cross domain calls to the service. I have most of the things working, but when I try to call the function it always gives me a error -HTTP 400 Bad Request

I used Fiddler to capture the error and it says something like this

enter image description here

When I tried to find solutions, I saw people suggesting to use BodyStyle=WebMessageBodyStyle.Bare. I tried that and the service was giving errors because I have more than one parameters.

[OperationContract]
        [WebInvoke(Method = "POST",
                    BodyStyle=WebMessageBodyStyle.Wrapped,
                    RequestFormat=WebMessageFormat.Json,
                    ResponseFormat=WebMessageFormat.Json,
                    UriTemplate = "/GetData")]
        //[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetData/{value}/")]
        string GetData(string value, string val2);

I am not sure how to solve this problem. Any help will be appreciated.

If you need to look at anything more, like my config please let me know and I can share it.

SERVICE CALL:

var datav = "{value : 4, val2 : 5}";
            var datasent = JSON.stringify(datav);
    $.ajax({
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: datasent,
            url: pURL,
            success: function (data) {
            alert('success');
            },
            error: function(xhr, status, error) {
              alert(xhr.responseText);
            }
            });
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Ron
  • 886
  • 13
  • 39

1 Answers1

1

First of all, it is not recommended to use POST if your Service is just returning data. Use GET instead. But still, if you are going to use POST, then here is the proper method to use it in WCF.

[OperationContract]
[WebInvoke(Method = "POST",
  BodyStyle=WebMessageBodyStyle.Bare,
  RequestFormat=WebMessageFormat.Json,
  ResponseFormat=WebMessageFormat.Json,
  UriTemplate = "/GetData")]    
string GetData(MyValues values);

And here is your MyValues class.

[DataContract]
public class MyValues
{
   [DataMember]
   public string value1{get; set;}

   [DataMember]
   public string value2{get; set;}

   public override string ToString()
   {
      JavaScriptSerializer js = new JavaScriptSerializer(); // Available in   System.Web.Script.Serialization;           
      return js.Serialize(this);
   }
}

Note that I have written, ToString() method in MyValues class. This is because you can get the format of JSON that you will send from JSON call. More details here.

When calling from AJAX, you need to specify charset as well.

contentType: "application/json; charset=utf-8",

Check now! Make sure that you are sending right JSON in your request. ToString() method will return you the required JSON format that your service will accept.

Community
  • 1
  • 1
Faizan Mubasher
  • 4,427
  • 11
  • 45
  • 81
  • Thank you for the answer, I tried but it still gives me the same error. My method on the service has two parameters and that forces me to use a 'Wrapped' request. Should I move them into a class? – Ron Mar 21 '14 at 14:21
  • Make an object of MyValues class and call ToString() method. It will return you the JSON format. Keep that JSON format save and send JSON in that particulat format that ToString() method returned from your AJAX call. – Faizan Mubasher Mar 21 '14 at 14:26
  • I am not sure if I am doing this right. But I still get the error. – Ron Mar 21 '14 at 14:34
  • OperationFormatter encountered an invalid Message body. Expected to find an attribute with name 'type' and value 'object'. Found value 'array'.' is the new error – Ron Mar 21 '14 at 14:35
  • Thank you. I figured that out, but now I am getting a NULL Reference Exception. working on resolving that. – Ron Mar 21 '14 at 14:42
  • When I try to read the values inside my object on the server side (service) I get a null reference error – Ron Mar 21 '14 at 14:44
  • Do I have to perform any kind of deserialization on the server ? – Ron Mar 21 '14 at 14:47
  • No, WCF automatically do it for you. – Faizan Mubasher Mar 21 '14 at 14:48
  • Ok, I was able to get the desired response back from the webservice, but the ajax call still goes to the "error" even when fiddler shows me a HTTP 200 and the response. – Ron Mar 21 '14 at 16:09
  • The error is because the response json is padded in quotes "" and that makes it a string and it produces a invalid json. I used jsonlint to check and it gives a parser error – Ron Mar 21 '14 at 16:18