我有一个带有多个参数的方法的WCF Rest服务:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)]
StatusMessage DoSomeWork(short myId, decimal latitude, decimal longitude, string someData);
在客户端序列化的JSON数据正确序列化,并且此方法接收该数据。问题是,longitude
参数始终返回0,无论该序列化值是什么值。所有其他参数都正确反序列化。知道为什么会发生这种情况,以及可能的解决办法吗?
答案 0 :(得分:1)
确保JSON对象中的属性名称与参数longitude
的名称匹配。下面的代码显示了您的确切操作合同,并且服务正确接收了经度。
public class StackOverflow_23529686
{
[ServiceContract]
public class Service
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json)]
public StatusMessage DoSomeWork(short myId, decimal latitude, decimal longitude, string someData)
{
return new StatusMessage
{
Text = string.Format("id={0}, lat={1}, lon={2}, data={3}", myId, latitude, longitude, someData)
};
}
}
public class StatusMessage
{
public string Text { get; set; }
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
c.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var json =
"{'someData':'hello','longitude':-56.78,'latitude':12.34,'myId':1}"
.Replace('\'', '\"');
Console.WriteLine(c.UploadString(baseAddress + "/DoSomeWork", json));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}