用于WCF REST服务的JSON.NET序列化器 [英] JSON.NET Serializer for WCF REST Services
问题描述
我正在尝试使用 NETFx Json.NET MediaTypeFormatter nuget包进行交换在我的WCF REST服务(4.0框架)中淘汰默认的DataContractJsonSerializer.我将包下载到了我的项目中,并在Global.asax文件中添加了以下代码行.
I am trying to use the NETFx Json.NET MediaTypeFormatter nuget package to swap out the default DataContractJsonSerializer in my WCF REST service (4.0 framework). I downloaded the package in my project and added the following lines of code in the Global.asax file.
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create();
config.Configuration.OperationHandlerFactory.Formatters.Clear();
config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
}
但是当我运行该服务时,它仍然使用DataContractJsonSerilizer进行序列化.下面是我从服务中返回的课程.
But when I run the service it still uses the DataContractJsonSerilizer for serialization. Below is the class I am returning from my service.
[DataContract]
public class SampleItem
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string StringValue { get; set; }
[DataMember]
public DateTime DateTime { get; set; }
}
下面是Fiddler中服务的响应.
Below is the response from the service in Fiddler.
您可以看到DateTime不是我在上述代码的serializerSettings中指定的ISO格式.这告诉我JSON.NET序列化程序不用于序列化对象.
You can see that the DateTime is not in ISO format which I have specified in serializerSettings in the above code. This tells me that the JSON.NET serializer is not used for serializing the objects.
非常感谢您的帮助.
推荐答案
找到答案后,我感到很傻.有时会发生:).我必须将配置添加到RouteTable.以下是Global.asax中的代码
I feel dumb after I figured the answer. Happens at times :). I had to add the config to the RouteTable. Below is the code in Global.asax
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create().Configuration;
config.OperationHandlerFactory.Formatters.Clear();
config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
var httpServiceFactory = new HttpServiceHostFactory
{
OperationHandlerFactory = config.OperationHandlerFactory,
MessageHandlerFactory = config.MessageHandlerFactory
};
RouteTable.Routes.Add(new ServiceRoute("Service1", httpServiceFactory, typeof(Service1)));
}
}
希望碰巧遇到相同情况的人会有所帮助.
Hope it will help somebody if they happen to run into the same scenario.
这篇关于用于WCF REST服务的JSON.NET序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!