gpt4 book ai didi

c# - ServiceStack.Text 在应用程序启动时设置 JsConfig

转载 作者:行者123 更新时间:2023-11-30 21:47:50 26 4
gpt4 key购买 nike

我在我的asp net mvc应用程序的Application_Start方法中设置了JsConfig

 protected void Application_Start()
{
JsConfig.DateHandler = JsonDateHandler.ISO8601;
JsConfig.EmitCamelCaseNames = true;
}

然后我想在我的服务方法中使用扩展方法 ToJson,例如

public string testMethod{
//here code
var obj = new TestObj{
Id = 1,
CurrentDate = DateTime.Now
}
return obj.ToJson();
}

然后我查看结果,我看到 json 结果采用 PascalCase 格式,日期格式如下 Date(123455678990),但在我在配置中设置使用 camelCase 和 utc 格式日期之前

但我在我的服务方法中设置了配置,例如:

public string testMethod{
//here code
JsConfig.DateHandler = JsonDateHandler.ISO8601;
JsConfig.EmitCamelCaseNames = true;
var obj = new TestObj{
Id = 1,
CurrentDate = DateTime.Now
}
return obj.ToJson();
}

我得到了我想要的结果

是否可以在启动我的应用程序时设置 JsConfig 属性?

最佳答案

在 Global.asax 中的 Application_Start() 处设置 JsConfig 属性确实按预期设置了 JSON 序列化首选项的全局配置。

我在测试 MVC 项目中添加了一个示例 in this commit按预期工作,在 Application_Start() 中设置静态 JsConfig 配置:

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
JsConfig.Init(new Config {
DateHandler = DateHandler.ISO8601,
TextCase = TextCase.CamelCase
});
//...
}
}

并在 Controller 中序列化 JSON:

return new HomeViewModel
{
Name = name,
Json = new TestObj { Id = 1, CurrentDate = DateTime.Now }.ToJson()
};

按预期序列化:

{"id":1,"currentDate":"2016-06-29T11:56:45.7517089-04:00"}

关于c# - ServiceStack.Text 在应用程序启动时设置 JsConfig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38104129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com