tags:

views:

325

answers:

2
  [WebInvoke(Method = "PUT", UriTemplate = "users/{username}")]
  [OperationContract]
  void PutUser(string username, User newValue);//update a user

I have a update user method defined as showed above. Then I use a HttpWebRequest to test the method, but how can I pass the User object with this HttpWebResquest? The following code is what I got so far.

     string uri = "http://localhost:8080/userservice/users/userA";
     HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
     req.Method = "PUT";
     req.ContentType = " application/xml";
     req.Proxy = null;
A: 

In WCF/REST you don't pass an object, you pass a message.

If I were doing this, as a first step, I would create a WCF client that interacts with the service. I would examine the messages passed on the wire by the WCF client, and then I'd replicate that message with the HttpWebRequest.

Cheeso
thanks for the hints
crocpulsar
+1  A: 
   string uri = "http://localhost:8080/userservice/users/userA";
   string user = "<User xmlns=\"http://schemas.datacontract.org/2004/07/RESTful\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"&gt;&lt;DOB&gt;2009-01-18T00:00:00&lt;/DOB&gt;&lt;Email&gt;[email protected]&lt;/Email&gt;&lt;Id&gt;1&lt;/Id&gt;&lt;Name&gt;Sample  User</Name><Username>userA</Username></User>";
        byte[] reqData = Encoding.UTF8.GetBytes(user);

        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
        req.Method = "POST";
        req.ContentType = " application/xml";
        req.ContentLength = user.Length;
        req.Proxy = null;
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(reqData, 0, reqData.Length);

        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
        string code = resp.StatusCode.ToString();

        //StreamReader sr = new StreamReader( resp.GetResponseStream());
        //string respStr = sr.ReadToEnd();
        Console.WriteLine(code);
        Console.Read();

I found the solution, I need to construct the xml string I want to pass and then write it into stream

crocpulsar