3

Question

Is there an up-to-date example showing how to replace the default DataContractJsonSerializer with Json.Net serializer in a WCF 4.5 Service?

Background

As seems to be a common request, I want to replace the default DataContractJsonSerializer with Json.Net serializer. The first approach I came across was provided by Carlos Figueira here. This does work, but as pointed out at the end of the article (paraphrasing somewhat):

this is not production-ready code...tested it for a few contracts...cannot guarantee that it will work for all scenarios…for simplicity sake it doesn’t have a lot of error handling which a production-level code would...it’s not too easy to integrate any new formats in the existing WCF REST pipeline...had to deal with formatters, Message objects, take a dependency on a content type mapper, just to be able to use this different serializer...even after all of this...not completely integrated with the pipeline – UriTemplates aren’t supported...

Which all makes me a bit nervous. However at the end there is a mention of WCF API with a link to an discussion which has these lines of code:

var hostConfig = (HttpHostConfiguration) config;
hostConfig.OperationHandlerFactory.Formatters.Insert(0, new NewtonsoftJsonFormatter());

as well as how to override a formatter. The problem is that I can't get this to work in a WCF service. After including a bunch of additional NuGet packages the formatter compiles, but my service is never called. Each page I come across, seems to have different configuration code. I have tried the approaches outlined here, here, here, here and here (to list a few). Some use HttpHostConfiguration, some use GlobalConfiguration, some use OperationHandlerFactory. I think that part of the problem is that a number of these approaches are old and from different technologies - WCF WEB API, ASP.NET API, ASP.NET MVC.

While I can get the formatter to compile, it is never called, which makes me think that it is a configuration issue. I could post some code, but I am not sure exactly which part is incorrect. I have considered the approach of returning the generic Message object and formatting each object to a Message with json, but I would prefer to only do this as a last resort as it makes the return types for the service less clear. Which brings me to my the question show above.

Community
  • 1
  • 1
acarlon
  • 16,764
  • 7
  • 75
  • 94

0 Answers0