[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json)]
public string StudentUsers(Student user)
{
return string.Format("Hello {0}", user.Name);
}
上面的代碼是我的REST服務。而我的客戶代碼是:RESTfull Service不接受對象作爲參數
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
Student user =
new Stuent {
Name="Test User",
Email = "[email protected]",
Password = "test"
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(user.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, user);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
}
我的服務託管,我使用webHttpBinding。當我調試我的REST服務時,我在Student對象中收到null
。我相信我的post方法發送數據是通過在REST服務中將名稱,電子郵件和密碼作爲參數進行測試,因此我的數據已成功發佈,但發佈的Json數據並未轉換爲Student對象。我在某處讀到RESTfull Service會將該Json數據轉換爲對象。這是真的,還是我們需要明確地轉換它?
您可以使用提琴手來確定服務器獲取POST-ed數據嗎?請求的返回值是多少?是400,500,200嗎? – wal 2012-08-03 13:25:20