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);
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\"";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With