.net - 如何使用 JSON 将 TimeSpan 对象传递给 WCF 方法

标签 .net wcf json rest timespan

我试图找到一种使用 JSON 调用 WCF 方法并将 TimeSpan 作为参数传递的方法,但我总是收到来自服务的“错误请求”响应。

这是一个片段代码服务接口(interface):

 [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    TimeSpan GetTimeSpan(TimeSpan value);

服务电话:
  String method = "GetTimeSpan";
  String result = null;

  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + method);
  request.KeepAlive = false;
  request.Method = WebRequestMethods.Http.Post;
  request.ContentType = "application/json";

  JsonSerializer serializer = new JsonSerializer();

  TimeSpan ts = new TimeSpan(23, 59, 59);
  String jsonString = JsonConvert.SerializeObject(ts);


  String data = jsonString;      //jsonString = "23:59:59"
  //I have already tryed with {"value": "23:59:59"} and the result is the same, bad request.
  request.ContentLength = data.Length;

  StreamWriter writer = new StreamWriter(request.GetRequestStream());
  writer.Write(data);
  writer.Close();

  WebResponse response = request.GetResponse();
  StreamReader reader = new StreamReader(response.GetResponseStream());
  result = reader.ReadToEnd();
  response.Close();

这只是一个例子。在没有 TimeSpan 的情况下调用服务时一切正常。我需要让它工作,以便与以典型方式使用服务的其他客户端保持兼容性。

回复:

远程服务器返回错误:(400) 错误请求。

我是否传递了错误的 TimeSpan json 表示?或者有没有办法定义在服务处理请求时如何反序列化 TimeSpan?

提前致谢

最佳答案

TimeSpan 的格式WCF 使用的与 Newtonsoft JSON 序列化程序 (JSON.NET) 使用的不同。您可以使用 DataContractJsonSerializer 序列化一个 TimeSpan 实例。 (DCJS),这将是 WCF REST 服务所需的格式。

下面的代码会打印出一些TimeSpan的格式由 JSON.NET 和 DCJS 序列化的值:

public class StackOverflow_7178839
{
    public static void Test()
    {
        foreach (var ts in new TimeSpan[] { new TimeSpan(23, 59, 59), new TimeSpan(3, 4, 5, 6), new TimeSpan(-4, 3, 4, 5, 333) })
        {
            Console.WriteLine("For TimeSpan value: {0}", ts);
            Console.WriteLine("  {0}", Newtonsoft.Json.JsonConvert.SerializeObject(ts));
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(TimeSpan));
            MemoryStream ms = new MemoryStream();
            dcjs.WriteObject(ms, ts);
            Console.WriteLine("  {0}", Encoding.UTF8.GetString(ms.ToArray()));
        }
    }
}

关于.net - 如何使用 JSON 将 TimeSpan 对象传递给 WCF 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7178839/

相关文章:

.net - GetCustomAttribute() 对 AssemblyVersionAttribute 返回 null

wcf - 连接被拒绝 - 工作中的 nettcp WCF 服务 - 客户端通过 VPN 连接

c# - 如何在单个控制台主机中托管多个 WCF 服务?

c# - 解析 WCF ProtocolException 时出现 System.ServiceModel.CommunicationException

json - 如何正确将 JSON 数据发送到 phx phoenix API

json - 为什么 golang 自定义解码得到零结构

c# - C#中一个简单线程池的代码

c# - 执行身份验证请求返回意外结果 : 404

javascript - 如何在 JavaScript 中读取外部本地 JSON 文件?

c# - EF Core 过滤 + 子实体分页