用于 WCF REST 服务的 JSON.NET 序列化器

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

我正在尝试使用 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 中服务的响应。

enter image description here

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

非常感谢任何帮助。

最佳答案

在我找到答案后,我感到很愚蠢。有时会发生:)。我必须将配置添加到路由表中。下面是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 REST 服务的 JSON.NET 序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827933/

相关文章:

c# - System.Net.Http 与 Microsoft.Net.Http 的现状

c# - WCF 底层连接关闭 : An unexpected error occurred on a receive

asp.net - 将 JSON 数组传递到 WCF Web 服务

c# - 使用 Json.NET (C#) 从 json 中以字符串形式读取子对象

vb.net - JSON.Net - 反序列化对象格式

c# - 获取输出数据返回 0

c# - WCF REST - "Get"使用复杂类型

c# - 如何将名称-值对数组的 JSON 数组反序列化为 List<MyClass>

c# - 遍历通用对象属性

c# - 无法加载文件或程序集 'Microsoft.Practices.EnterpriseLibrary.Common' 或其依赖项之一