2009-10-12 83 views
1
[WebInvoke(Method = "PUT", UriTemplate = "users/{username}")] 
    [OperationContract] 
    void PutUser(string username, User newValue);//update a user 

我有一個更新用戶方法定義如上所示。然後我使用HttpWebRequest來測試這個方法,但是我怎麼能通過這個HttpWebResquest傳遞User對象呢? 以下代碼是我到目前爲止得到的。傳遞對象與WCF RESTful

 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; 

回答

1

在WCF/REST中,您不傳遞對象,而是傳遞消息。

如果我這樣做,作爲第一步,我將創建一個與服務交互的WCF客戶端。我將檢查由WCF客戶端傳遞的消息,然後使用HttpWebRequest複製該消息。

+0

謝謝你的提示 – 2009-10-12 06:41:42

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>[email protected]</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字符串我想通過,然後將其寫入流