用于WCF REST服务的JSON.NET Serializer

我试图使用 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序列化程序不用于序列化对象.

非常感谢任何帮助.

我找到答案后感到愚蠢.有时发生:).我不得不将配置添加到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)));
    }
}

希望它能帮助某人,如果他们碰巧遇到同样的情况.

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...