反序列化请求时,我得到一个非空但为空的字典。
我要发布的对象:
public class Data
{
public IDictionary<string, object> Dictionary { get; set; }
}
这是我随请求发送的正文:
{"Dictionary":{"key1":"value1","foo":"bar"}}
内置序列化程序创建一个Data
空的对象Dictionary
。Newtonsoft 序列化程序的行为符合我的要求。因此,经过一番谷歌搜索后,我将服务合同更改为接受 aStream
而不是Data
.
using Newtonsoft.Json;
[ServiceContract]
interface IMyServiceContract
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "data",
RequestFormat = WebMessageFormat.Json)]
void PostData(Stream body);
}
class MyServiceContract : IMyServiceContract
{
void PostData(Stream body)
{
using (var reader = new StreamReader(body))
json = reader.ReadToEnd();
data = JsonConvert.DeserializeObject<Data>(json);
// ...
}
}
这里的主要问题是,如果我指定 header ,则不再接受请求Content-Type: application/json
,这显然是我想要的,但如果提到方法签名也会很好Data
。
如何为我的服务指定自定义反序列化器?或者,如果不可能,即使指定了 Content-Type,也要使当前解决方案工作?