ServiceStack DateTime數據類型轉Json出現的困擾
阿新 • • 發佈:2019-03-21
onf 導致 metadata tac cti add info != postman
執行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. publicvoid 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出現的困擾