我试图找到一种使用 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/