Serializing an object into the body of a WCF request using webHttpBinding
- by Bert
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();