2012-02-04 155 views
1

我需要用4串POST方法創建一個REST服務參數WCF REST服務POST方法

我把它定義爲如下:

[WebInvoke(UriTemplate = "/", Method = "POST", BodyStyle= WebMessageBodyStyle.WrappedRequest)] 
public Stream ProcessPost(string p1, string p2, string p3, string p4) 
{ 
    return Execute(p1, p2, p3, p4); 
} 

而且我想如下的代碼來調用它:

 string result = null; 
     HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; 
     req.Method = "POST"; 
     req.ContentType = "application/x-www-form-urlencoded"; 

     string paramz = string.Format("p1={0}&p2={1}&p3={2}&p4={3}", 
      HttpUtility.UrlEncode("str1"), 
      HttpUtility.UrlEncode("str2"), 
      HttpUtility.UrlEncode("str3"), 
      HttpUtility.UrlEncode("str4") 
      ); 

     // Encode the parameters as form data: 
     byte[] formData = 
      UTF8Encoding.UTF8.GetBytes(paramz); 
     req.ContentLength = postData.Length; 

     // Send the request: 
     using (Stream post = req.GetRequestStream()) 
     { 
      post.Write(formData, 0, formData.Length); 
     } 

     // Pick up the response: 
     using (HttpWebResponse resp = req.GetResponse() 
             as HttpWebResponse) 
     { 
      StreamReader reader = 
       new StreamReader(resp.GetResponseStream()); 
      result = reader.ReadToEnd(); 
     } 

     return result; 

但是,客戶端代碼返回碼400:壞請求

我是什麼做錯了嗎?

謝謝

+0

嘗試啓用WCF跟蹤以查看問題是什麼,但我認爲該服務需要XML – 2012-02-04 21:21:58

回答

1

我想說申報UriTemplate的參數,如下面

[OperationContract] 
[WebInvoke(UriTemplate = "{p1}/{p2}/{p3}/{p4}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
string ProcessPost(string p1, string p2, string p3, string p4); 

,並使用下面的代碼來調用,

string result = null; 
string uri = "http://localhost:8000/ServiceName.svc/1/2/3/4"; 

HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; 
req.KeepAlive = false; 
req.Method = "POST"; 

using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) 
    { 
     StreamReader reader = new StreamReader(resp.GetResponseStream()); 
     result = reader.ReadToEnd(); 
    } 

它工作正常的我。希望這種方法很有幫助。