NeedACar
NeedACar

Reputation: 951

WCF JSON POST request, single string parameter not binding and returning 400

In my WCF (azure cloud) service, I want to support JSON. I am creating some test methods to see if everything works. I can get the GET calls to work, but when I'm doing a POST with a simple parameter I will always get:

The remote server returned an error: (400) Bad Request.

If I don't send a parameter, it will execute the method, but with a null value as parameter of course. I tried different formats of JSON and WebMessageBodyStyle, but none seem to work.

If I change the parameter type to Stream I receive the data, but I have to manually deserialize it. This shouldn't be necessary right?

Interface:

        [OperationContract]
        [WebInvoke(UriTemplate = "Test",
            Method = "POST", 
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        string Test(string data);

Impl:

        public string Test(string data)
        {           
            return "result is " + data;
        } 

Test client:

            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
            client.Encoding = System.Text.Encoding.UTF8;
            string jsonInput = "{'data':'testvalue'}";
            string postResponse = client.UploadString(postUrl, jsonInput);
            Console.WriteLine("post response: " + postResponse);

Upvotes: 9

Views: 5720

Answers (1)

NeedACar
NeedACar

Reputation: 951

The golden combination was to use double quotes in the JSON code combined with WebMessageBodyStyle.WrappedRequest.

Working JSON:

   string jsonInput = "{\"data\":\"testvalue\"}";

When setting WebMessageBodyStyle to Bare, the following JSON works:

   string jsonInput = "\"testvalue\"";

Upvotes: 13

Related Questions