【问题标题】:JSON.NET Serializer for WCF REST ServicesWCF REST 服务的 JSON.NET 序列化程序
【发布时间】:2012-04-07 08:21:06
【问题描述】:

我正在尝试使用NETFx Json.NET MediaTypeFormatter nuget 包来换出我的 WCF REST 服务(4.0 框架)中的默认 DataContractJsonSerializer。我在我的项目中下载了包,并在 Global.asax 文件中添加了以下代码行。

    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 进行序列化。下面是我从服务中返回的课程。

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

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

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

以下是 Fiddler 中服务的响应。

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

不胜感激。

【问题讨论】:

    标签: json.net nuget wcf-rest wcf-web-api nuget-package


    【解决方案1】:

    在我想出答案后,我感到很愚蠢。有时会发生:)。我必须将配置添加到 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)));
        }
    }
    

    希望如果他们碰巧遇到同样的情况,它会有所帮助。

    【讨论】:

    • 其实我也遇到过类似的情况,但是我的 WCF 服务托管在 Windows 服务中。上面的代码引发以下异常:“System.InvalidOperationException: 'ServiceHostingEnvironment.EnsureServiceAvailable' 无法在当前托管环境中调用。此 API 要求调用应用程序托管在 IIS 或 WAS 中。”有什么想法吗?
    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2013-02-05
    • 2015-03-21
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多