【问题标题】:WCF Rest Service has value deserializing as 0 every timeWCF Rest Service 每次都将值反序列化为 0
【发布时间】:2014-05-07 22:37:05
【问题描述】:

我有一个 WCF Rest 服务,它的方法接受多个参数:

[OperationContract]        
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)]
StatusMessage DoSomeWork(short myId, decimal latitude, decimal longitude, string someData);

在客户端序列化的 JSON 数据正确序列化,并且该方法接收该数据。问题是 longitudeparameter always 返回为 0,无论该值在序列化时是什么值。所有其他参数都已正确反序列化。知道为什么会发生这种情况,以及可能的解决方法吗?

【问题讨论】:

  • 如何将数据发送到服务?你能发布一个你在做什么的例子吗?
  • 我通过 WebClient 将它作为 JSON 发送。我目前无法发布示例,但这是通过 WebService 将字符串发布为 JSON 的标准方式;没什么特别的。

标签: c# .net json wcf


【解决方案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();
    }
}

【讨论】:

  • 这成功了——我有一个参数拼写错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 2012-01-20
  • 2018-04-02
  • 2012-02-19
  • 2021-12-22
  • 2019-01-05
  • 2011-12-19
  • 1970-01-01
相关资源
最近更新 更多