9

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

1 Answer 1

13

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\"";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.