【发布时间】:2011-08-24 16:18:34
【问题描述】:
我正在尝试找到一种使用 JSON 调用 WCF 方法并将 TimeSpan 作为参数传递的方法,但我总是收到来自服务的“错误请求”响应。
这里是一个sn-p代码服务接口:
[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) Bad Request。
我是否传递了错误的 TimeSpan json 表示?或者有没有办法定义在服务处理请求时如何反序列化 TimeSpan?
提前致谢
【问题讨论】:
-
TimeSpan 无法序列化。 stackoverflow.com/questions/3232701/…的可能重复
-
@dennis - 这个问题是关于 .NET 3.5 上的 WCF(使用 VS2008 是一个相当好的假设)。也许自 .NET 4.0 以来这已经改变了?也许 OP 可以澄清 .NET 版本?
标签: .net wcf json rest timespan