2010-10-22 72 views
0

我有一個簡單的OpenRasta web服務和Web服務的控制檯客戶端。如何使用OpenRasta處理POST方法?

使用GET方法是很容易 - 我定義得到OpenRasta,當客戶端使用此代碼,這一切工作正常

HttpWebRequest request = WebRequest.Create("http://localhost:56789/one/two/three") as HttpWebRequest; 

// Get response 
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
{ 
    // Get the response stream 
    StreamReader reader = new StreamReader(response.GetResponseStream()); 

    // Console application output 
    Console.WriteLine(reader.ReadToEnd()); 

然而,當我嘗試使用POST這樣

Uri address = new Uri("http://localhost:56789/"); 

    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; 
    request.Method = "POST"; 
    request.ContentType = "application/x-www-form-urlencoded"; 

    string one = "one"; 
    string two = "two"; 
    string three = "three"; 

    StringBuilder data = new StringBuilder(); 
    data.Append(HttpUtility.UrlEncode(one)); 
    data.Append("/" + HttpUtility.UrlEncode(two)); 
    data.Append("/" + HttpUtility.UrlEncode(three)); 

    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); 
    request.ContentLength = byteData.Length; 

    // Write data 
    using (Stream postStream = request.GetRequestStream()) 
    { 
    postStream.Write(byteData, 0, byteData.Length); 
    } 

    // Get response 
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
    { 
    StreamReader reader = new StreamReader(response.GetResponseStream()); 
    Console.WriteLine(reader.ReadToEnd()); 
    } 
    Console.ReadKey(); 
} 

我得到500內部服務器錯誤,我不知道如何在OpenRasta web服務中處理這個問題。如何在Openrasta中定義POST方法?有什麼建議麼?

+1

您的處理程序的代碼將是有用的。 – 2010-10-22 13:19:57

回答

2

您提供的代碼會發送「one/two/three」,並將其放在您的請求的內容中,並使用媒體類型「application/x-www-form-urlencoded」,這可能是您的問題出在哪裏,因爲您編碼的內容與您指定的媒體類型無關。

不知道你的處理程序是什麼樣的,我不能告訴你你應該把它放在裏面。但是我可以告訴你,如果你發送參數,它應該看起來像key = value & key2 = value2,與URI中的內容無關(你的/ one/two/three例子)。