执行 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 再次取得该字符串时间, 就可以正确的识别时间类型字段了.
来源: http://www.bubuko.com/infodetail-2994451.html