2012-03-22 57 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

相關問題