2

I set JsConfig in Application_Start method in my asp net mvc application

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

and then I want to use extension method ToJson in my service method, for example

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

and then I look a result and I see that json result in PascalCase and date in following format Date(123455678990), but before I set in config for use the camelCase and utc format date

but I set config in my service method, for example:

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

I get the result that I want

Is it possible to set JsConfig properties on start my application?

netwer
  • 737
  • 11
  • 33

1 Answers1

3

Setting the JsConfig properties at Application_Start() in your Global.asax does set the global configuration for your JSON serialization preferences as expected.

I've added an example of this in a test MVC Project in this commit which is working as expected, that sets static JsConfig configuration in Application_Start():

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

And serializes JSON in a controller:

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

Which serializes as expected:

{"id":1,"currentDate":"2016-06-29T11:56:45.7517089-04:00"}
mythz
  • 141,670
  • 29
  • 246
  • 390