Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

rest

c#

.net

wcf

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);
like image 581
NeedACar Avatar asked Jun 04 '15 20:06

NeedACar


1 Answers

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\"";
like image 89
NeedACar Avatar answered Sep 21 '22 14:09

NeedACar