Set default global json serializer settings

后端 未结 4 2115
你的背包
你的背包 2020-11-27 06:33

I\'m trying to set the global serializer settings like this in my global.asax.

var formatter = GlobalConfiguration.Configuration.Formatters.Json         


        
相关标签:
4条回答
  • 2020-11-27 07:17

    Accepted answer did not work for me. In .netcore, I got it working with...

    services.AddMvc(c =>
                     {
                     ....
                     }).AddJsonOptions(options => {
                         options.SerializerSettings.Formatting = Formatting.Indented;
                         ....
                     })
    
    0 讨论(0)
  • 2020-11-27 07:17

    Just do the following in your action so that you can return a content-negotiated response and also your formatter settings can take effect.

    return Request.CreateResponse(HttpStatusCode.OK, page);
    
    0 讨论(0)
  • 2020-11-27 07:24

    Setting the JsonConvert.DefaultSettings did the trick.

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        TypeNameHandling = TypeNameHandling.Objects,
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    
    0 讨论(0)
  • 2020-11-27 07:34

    You're correct about where to set the serializer. However, that serializer is used when the request to your site is made with a requested content type of JSON. It isn't part of the settings used when calling SerializeObject. You could work around this by exposing the JSON serialization settings defined global.asax via a property.

    public static JsonSerializerSettings JsonSerializerSettings
    {
        get
        {
            return GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
        }
    }
    

    And then use this property to set the serialization settings when doing serialization within your controllers:

    return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(JsonConvert.SerializeObject(page, WebApiApplication.JsonSerializerSettings))
    };
    
    0 讨论(0)
提交回复
热议问题