views:

436

answers:

2

I have a WCF service exposed with a webHttpBinding endpoint.

[OperationContract(IsOneWay = true)]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, 
    BodyStyle = WebMessageBodyStyle.Bare, 
    UriTemplate = "/?action=DoSomething&v1={value1}&v2={value2}")]
void DoSomething(string value1, string value2, MySimpleObject value3);

In theory, if I call this, the first two parameters (value1 & value 2) are taken from the Uri and the final one (value3) should be deserialized from the body of the request.

Assuming I am using Json as the RequestFormat, what is the best way of serialising an instance of MySimpleObject into the body of the request before I send it ? This, for instance, does not seem to work :

HttpWebRequest sendRequest = (HttpWebRequest)WebRequest.Create(url);
sendRequest.ContentType = "application/json";
sendRequest.Method = "POST";
using (var sendRequestStream = sendRequest.GetRequestStream())
{
    DataContractJsonSerializer jsonSerializer = 
        new DataContractJsonSerializer(typeof(MySimpleObject));
    jsonSerializer.WriteObject(sendRequestStream, obj);
    sendRequestStream.Close();
}
sendRequest.GetResponse().Close();
A: 

One thing I'd do differently is to put the WebResponse into a using block:

using (var response = sendRequest.GetResponse())
{
}

I'd be concerned about what happens if the Close throws an exception in your code.

Also, are you logging exceptions? You might want to try:

try
{
    using (var response = sendRequest.GetResponse())
    {
    }
}
catch (Exception ex) {
    Console.WriteLine(ex.ToString()); // Or however you want to display it
    throw;
}

This will ensure that you know of any problems with the response (like a non-200 HTTP status).

John Saunders
There are no exceptions. The response code from the endpoint is 202 Accepted. I've been looking at the service trace logs and there were some mismatch errors in some cases and deserialization errors in others. I now have this working using both Json serialization (via both the DataContractJsonSerializedr and Json.Net) and using the XmlSerializer.
Bert
A: 

I now have this working using both Json serialization (via both the DataContractJsonSerializer and Json.Net) and using the XmlSerializer.

The odd thing is that the RequestFormat = WebMessageFormat.Xml property in the web invoke attribute seems to be ignored, i.e. inbound messages seem to be deserialized from xml or json regardless of this setting.

Bert
Could you post how you got it to work?
John Saunders