2012-06-20 44 views
0

對於任何不熟悉的Web API和序列化日期JSON,here's what I'm trying to do.的ASP.NET Web API - 序列化日期以JSON - 不能得到例如工作

它不是爲我工作,雖然,我的日期仍然得到序列化爲「/ Date(1039330800000-0700)/」。

這裏是我的JsonNetFormatter:

public class JsonNetFormatter : MediaTypeFormatter 
{ 
    private JsonSerializerSettings _jsonSerializerSettings; 

    public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings) 
    { 
     _jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings(); 

     // Fill out the mediatype and encoding we support 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); 
     Encoding = new UTF8Encoding(false, true); 
    } 

    protected override bool CanReadType(Type type) 
    { 
     if (type == typeof(IKeyValueModel)) 
     { 
      return false; 
     } 

     return true; 
    } 

    protected override bool CanWriteType(Type type) 
    { 
     return true; 
    } 

    protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) 
    { 
     // Create a serializer 
     JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); 

     // Create task reading the content 
     return Task.Factory.StartNew(() => 
     { 
      using (StreamReader streamReader = new StreamReader(stream, Encoding)) 
      { 
       using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) 
       { 
        return serializer.Deserialize(jsonTextReader, type); 
       } 
      } 
     }); 
    } 

    protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) 
    { 
     // Create a serializer 
     JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); 

     // Create task writing the serialized content 
     return Task.Factory.StartNew(() => 
     { 
      using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false }) 
      { 
       serializer.Serialize(jsonTextWriter, value); 
       jsonTextWriter.Flush(); 
      } 
     }); 


    } 
} 

和我的Global.asax.cs文件:

public class WebApiApplication : System.Web.HttpApplication 
{ 
    private static Logger Logger = NLog.LogManager.GetCurrentClassLogger(); 

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new HandleErrorAttribute()); 
     filters.Add(new WebApiApplication.Filters.ExceptionHandlingAttribute()); 
    } 

    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 

    protected void Application_Start() 
    { 
     RegisterDependencies(); 

     AreaRegistration.RegisterAllAreas(); 

     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 

     JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); 
     serializerSettings.Converters.Add(new IsoDateTimeConverter()); 
     GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(serializerSettings)); 

     BundleTable.Bundles.RegisterTemplateBundles(); 
    } 

    private void RegisterDependencies() 
    { 

     IUnityContainer container = new UnityContainer(); 
     container.RegisterInstance<IClientRepository>(new ClientRepository()); 

     GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
      t => 
      { 
       try 
       { 
        return container.Resolve(t); 
       } 
       catch (ResolutionFailedException) 
       { 
        return null; 
       } 
      }, 
      t => 
      { 
       try 
       { 
        return container.ResolveAll(t); 
       } 
       catch (ResolutionFailedException) 
       { 
        return new List<object>(); 
       } 
      }); 
    } 

    /// <summary> 
    /// Catches all exceptions. 
    /// </summary> 
    protected void Application_Error() 
    { 
     var exception = Server.GetLastError(); 

     Logger.Debug(exception); 
    } 
} 

從我讀過,這已經爲很多人的工作。我不確定我錯過了什麼?

回答

0

您是否刪除了默認添加到配置中的「舊」json格式化程序?認爲默認格式化工作,而不是你的。嘗試刪除默認的Json formater,然後再添加您的默認Json formater

+0

我添加了GlobalConfiguration.Configuration.Formatters.Clear();就在我添加新格式化程序之前。我通過斷點驗證了JsonNetFormatter正在被擊中。當我在Fiddler中觀看請求/響應時,但是這是我得到的唯一回應: 'HTTP/1.1 200 OK 服務器:ASP.NET Development Server/10.0.0.0 日期:2012年6月20日星期三20:47:52 GMT X-ASPNET-版本:4.0.30319 傳輸編碼:分塊 緩存控制:無緩存 雜注:無緩存過期 :-1 內容類型:應用程序/ JSON的; charset = utf-8 連接:關閉' 沒有身體? –

+0

我卸載了Beta版的MVC並安裝了RC,事情似乎更順暢。 –

+0

好的,非常感謝您提供的信息。同時建議您使用http://aspnetwebstack.codeplex.com/問題跟蹤器和郵件列表/討論那裏的beta或rc asp.net庫。會發生有關問題的更多信息 – Regfor