WCF JSON POST request, single-line parameter, non-binding and returning 400

In my WCF (Azure Cloud) service, I want to support JSON. I am creating several testing methods to see if everything works. I can get GET calls to work, but when I do a POST with a simple parameter, I always get:

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

If I do not send a parameter, it will execute this method, but with a null value as a parameter, of course. I tried different JSON and WebMessageBodyStyle formats, but no one works.

If I change the type of the parameter to Stream, I get the data, but I need to deserialize it manually. Is this not necessary?

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); 
+8
json c # rest wcf
source share
1 answer

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

Working JSON:

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

When setting up WebMessageBodyStyle on Bare, the following JSON works:

  string jsonInput = "\"testvalue\""; 
+8
source share

All Articles