[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json)]
public string StudentUsers(Student user)
{
return string.Format("Hello {0}", user.Name);
}
上面的代码是我的 REST 服务。我的客户代码是:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
Student user =
new Stuent {
Name="Test User",
Email = "test@test.com",
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 服务时,我收到null
了 Student 对象。我确信我的 post 方法正在发送数据,因为我通过将名称、电子邮件和密码作为 REST 服务的参数来测试它,因此我的数据已成功发布,但问题是我发布的 Json 数据没有转换为 Student 对象。我在某处读到 RESTfull 服务会将 Json 数据转换为对象。这是真的还是我们需要明确地转换它?