2012-03-22 46 views
8

我正尝试使用NETFx Json.NET MediaTypeFormatter nuget软件包替换掉我的WCF REST服务(4.0框架)中的默认DataContractJsonSerializer。我在我的项目中下载了软件包,并在Global.asax文件中添加了以下几行代码。适用于WCF REST服务的JSON.NET序列化程序

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)); 
    } 

但是,当我运行该服务时,它仍然使用DataContractJsonSeriler进行序列化。以下是我从我的服务中返回的班级。

[DataContract] 
public class SampleItem 
{ 
    [DataMember] 
    public int Id { get; set; } 

    [DataMember] 
    public string StringValue { get; set; } 

    [DataMember] 
    public DateTime DateTime { get; set; } 
} 

以下是来自Fiddler服务的响应。

enter image description here

你可以看到,日期时间是不是在我在serializerSettings在上面的代码中指定的ISO格式。这告诉我JSON.NET序列化程序不用于序列化对象。

希望有任何帮助。

回答

6

我想到了答案后,我感到哑巴。有时会发生:)。我不得不将配置添加到RouteTable。下面是在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))); 
    } 
} 

希望这将帮助别人,如果他们碰巧遇到了相同的情况。

+2

其实我碰巧遇到类似的情况,但我的WCF服务托管在Windows服务中。上面的代码会引发以下异常:“System.InvalidOperationException:'ServiceHostingEnvironment.EnsureServiceAvailable'无法在当前宿主环境中调用。此API要求调用应用程序驻留在IIS或WAS中。” 有什么想法? – 2012-03-29 09:56:02