Setting the default JSON serializer in ASP.NET MVC

前端 未结 2 1184
轮回少年
轮回少年 2020-11-22 06:08

I\'m working on an existing application that has been partially converted over to MVC. Whenever a controller responds with a JSON ActionResult, the enums are sent as number

2条回答
  •  长发绾君心
    2020-11-22 06:33

    In ASP.Net MVC4 the default JavaScript serializer which is used in the JsonResult class is still the JavaScriptSerializer (you can check it in the code)

    I think you have confused it with the ASP.Net Web.API where JSON.Net is the default JS serializer but MVC4 doesn't use it.

    So you need to configure JSON.Net to work with MVC4 (basically you need to create your own JsonNetResult), there are plenty of articles about it:

    • ASP.NET MVC and Json.NET
    • Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?

    If you also want to use JSON.Net for controller action parameters so during the model binding then you need write your own ValueProviderFactory implementation.

    And you need to register your implementation with:

    ValueProviderFactories.Factories
        .Remove(ValueProviderFactories.Factories
                                      .OfType().Single());
    ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
    

    You can use the built in JsonValueProviderFactory as an example or this article: ASP.NET MVC 3 – Improved JsonValueProviderFactory using Json.Net

提交回复
热议问题