JSON.NET Serial Set for WCF REST Services

I am trying to use the NETFx Json.NET MediaTypeFormatter nuget package to replace the standard DataContractJsonSerializer in my WCF REST service (4.0 framework)). I downloaded the package to 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)); } 

But when I start the service, it still uses the DataContractJsonSerilizer for serialization. Below is the class that 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; } } 

The following is a response from a service in Fiddler.

enter image description here

You can see that DateTime is not in the ISO format, which I specified in the serializerSettings parameters in the above code. This tells me that the JSON.NET serializer is not used to serialize objects.

Would thank for any help.

+8
nuget nuget-package wcf-rest wcf-web-api
source share
1 answer

I feel stupid after I understand the answer. It happens at times :). I had to add configuration to 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 this helps someone if they run into the same scenario.

+6
source share

All Articles