我试图使用
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中的代码
原文链接:https://www.f2er.com/json/288486.htmlpublic 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))); } }
希望它能帮助某人,如果他们碰巧遇到同样的情况.