首页 > Web开发 > 详细

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

时间:2019-03-21 10:06:00      阅读:216      评论:0      收藏:0      [点我收藏+]

执行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再次取得该字符串时间,就可以正确的识别时间类型字段了。

 

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

原文:https://www.cnblogs.com/joyswings/p/10569649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!