ServiceStack DateTime数据类型转Json出现的困扰

执行dotnet-new selfhost sstest 创建项目,然后打开解决方案

修改ssTest.ServiceModel中的Hello.cs,在HellopResponse中添加时间属性,然后修改MyServices中的代码

运行程序,打开Postman查看返回结果

 

 

 可以看到Json中date属性返回的是  "date": "/Date(1555810731732+0800)/",直接导致前段js无法识别该字段,该如何解决?

在Startup中加入以下代码,任何时间都转换为ISO8601字符串

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            JsConfig<DateTime>.SerializeFn = time => new DateTime(time.Ticks, DateTimeKind.Local).ToString("o");
            JsConfig<DateTime?>.SerializeFn =
                time => time != null ? new DateTime(time.Value.Ticks, DateTimeKind.Local).ToString("o") : null;
            JsConfig.DateHandler = DateHandler.ISO8601;

            app.UseServiceStack(new AppHost());

            app.Run(context =>
            {
                context.Response.Redirect("/metadata");
                return Task.FromResult(0);
            });
        }
    }

 

打开Postman再次运行,查看结果

 

前段js再次取得该字符串时间,就可以正确的识别时间类型字段了。

 

posted @ 2019-03-21 09:52  千军万马o  阅读(365)  评论(3编辑  收藏  举报