Définition du sérialiseur JSON par défaut dans ASP.NET MVC

Je travaille sur une application existante qui a été partiellement convertie en MVC. Chaque fois qu’un contrôleur répond avec un ActionResult JSON, les énumérations sont envoyées sous forme de nombres opposés au nom de la chaîne. Il semble que le sérialiseur par défaut devrait être JSON.Net, qui devrait envoyer les énumérations comme leurs noms opposés à la représentation entière, mais ce n’est pas le cas ici.

Est-ce que je manque un paramètre web.config qui le définit comme sérialiseur par défaut? Ou existe-t-il un autre paramètre à modifier?

Dans ASP.Net MVC4, le sérialiseur JavaScript par défaut utilisé dans la classe JsonResult est toujours le JavaScriptSerializer (vous pouvez le vérifier dans le code )

Je pense que vous l’avez confondu avec ASP.Net Web.API où JSON.Net est le sérialiseur JS par défaut mais que MVC4 ne l’utilise pas.

Donc, vous devez configurer JSON.Net pour qu’il fonctionne avec MVC4 (en gros, vous devez créer votre propre JsonNetResult ), il y a beaucoup d’articles à ce sujet:

  • ASP.NET MVC et Json.NET
  • Utiliser JSON.NET comme sérialiseur JSON par défaut dans ASP.NET MVC 3 – est-ce possible?

Si vous souhaitez également utiliser JSON.Net pour les parameters d’action du contrôleur, vous devez alors écrire votre propre implémentation ValueProviderFactory lors de la liaison du modèle.

Et vous devez enregistrer votre implémentation avec:

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

Vous pouvez utiliser le JsonValueProviderFactory comme exemple ou cet article: ASP.NET MVC 3 – JsonValueProviderFactory amélioré à l’aide de Json.Net

Correctif ASP.NET MVC 5:

Je n’étais pas prêt à passer à Json.NET pour le moment et dans mon cas, l’erreur se produisait pendant la requête. La meilleure approche dans mon scénario consistait à modifier l’actuel JsonValueProviderFactory qui applique le correctif au projet global et peut être effectué en éditant le fichier global.cs en tant que tel.

 JsonValueProviderConfig.Config(ValueProviderFactories.Factories); 

ajoutez une entrée web.config:

  

puis créez les deux classes suivantes

 public class JsonValueProviderConfig { public static void Config(ValueProviderFactoryCollection factories) { var jsonProviderFactory = factories.OfType().Single(); factories.Remove(jsonProviderFactory); factories.Add(new CustomJsonValueProviderFactory()); } } 

Il s’agit essentiellement d’une copie exacte de l’implémentation par défaut trouvée dans System.Web.Mvc mais avec l’ajout d’une valeur configurable web.config appsetting aspnet:MaxJsonLength .

 public class CustomJsonValueProviderFactory : ValueProviderFactory { /// Returns a JSON value-provider object for the specified controller context. /// A JSON value-provider object for the specified controller context. /// The controller context. public override IValueProvider GetValueProvider(ControllerContext controllerContext) { if (controllerContext == null) throw new ArgumentNullException("controllerContext"); object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext); if (deserializedObject == null) return null; Dictionary strs = new Dictionary(SsortingngComparer.OrdinalIgnoreCase); CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), ssortingng.Empty, deserializedObject); return new DictionaryValueProvider(strs, CultureInfo.CurrentCulture); } private static object GetDeserializedObject(ControllerContext controllerContext) { if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", SsortingngComparison.OrdinalIgnoreCase)) return null; ssortingng fullStreamSsortingng = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd(); if (ssortingng.IsNullOrEmpty(fullStreamSsortingng)) return null; var serializer = new JavaScriptSerializer() { MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength() }; return serializer.DeserializeObject(fullStreamSsortingng); } private static void AddToBackingStore(EntryLimitedDictionary backingStore, ssortingng prefix, object value) { IDictionary strs = value as IDictionary; if (strs != null) { foreach (KeyValuePair keyValuePair in strs) CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value); return; } IList lists = value as IList; if (lists == null) { backingStore.Add(prefix, value); return; } for (int i = 0; i < lists.Count; i++) { CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]); } } private class EntryLimitedDictionary { private static int _maximumDepth; private readonly IDictionary _innerDictionary; private int _itemCount; static EntryLimitedDictionary() { _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth(); } public EntryLimitedDictionary(IDictionary innerDictionary) { this._innerDictionary = innerDictionary; } public void Add(ssortingng key, object value) { int num = this._itemCount + 1; this._itemCount = num; if (num > _maximumDepth) { throw new InvalidOperationException("The length of the ssortingng exceeds the value set on the maxJsonLength property."); } this._innerDictionary.Add(key, value); } } private static ssortingng MakeArrayKey(ssortingng prefix, int index) { return ssortingng.Concat(prefix, "[", index.ToSsortingng(CultureInfo.InvariantCulture), "]"); } private static ssortingng MakePropertyKey(ssortingng prefix, ssortingng propertyName) { if (ssortingng.IsNullOrEmpty(prefix)) { return propertyName; } return ssortingng.Concat(prefix, ".", propertyName); } private static int GetMaximumDepth() { int num; NameValueCollection appSettings = ConfigurationManager.AppSettings; if (appSettings != null) { ssortingng[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers"); if (values != null && values.Length != 0 && int.TryParse(values[0], out num)) { return num; } } return 1000; } private static int GetMaxJsonLength() { int num; NameValueCollection appSettings = ConfigurationManager.AppSettings; if (appSettings != null) { ssortingng[] values = appSettings.GetValues("aspnet:MaxJsonLength"); if (values != null && values.Length != 0 && int.TryParse(values[0], out num)) { return num; } } return 1000; } }