Serializing an object into the body of a WCF request using webHttpBinding

Posted by Bert on Stack Overflow See other posts from Stack Overflow or by Bert
Published on 2009-08-03T21:34:03Z Indexed on 2010/05/31 12:03 UTC
Read the original article Hit count: 370

Filed under:
|
|
|
|

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();

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET