[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服务时,我在Student对象中接收null
。我确信我的post方法是在我通过在REST服务中将Name,Email和Password作为参数进行测试时发送数据,因此我的数据已成功发布但是我发布的Json数据未转换为Student对象。我在某处读到RESTfull服务会将该Json数据转换为对象。是真的还是我们需要明确转换它?
答案 0 :(得分:0)
答案 1 :(得分:0)
我已通过将WebInvoke更改为
来解决此问题[WebInvoke(Method="POST",UriTemplate="/Users",RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare)]