使用WCF RESTful传递对象

时间:2009-10-12 06:07:48

标签: wcf rest

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

我有一个如上所示定义的更新用户方法。然后我使用HttpWebRequest来测试方法,但是如何使用此HttpWebResquest传递User对象? 以下代码是我到目前为止所得到的。

     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;

2 个答案:

答案 0 :(得分:3)

   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\"><DOB>2009-01-18T00:00:00</DOB><Email>userA@example.com</Email><Id>1</Id><Name>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();

我找到了解决方案,我需要构建我要传递的xml字符串,然后将其写入流

答案 1 :(得分:1)

在WCF / REST中,您不传递对象,而是传递消息。

如果我这样做,作为第一步,我将创建一个与服务交互的WCF客户端。我将检查WCF客户端在线路上传递的消息,然后我将使用HttpWebRequest复制该消息。