C# 在ASP.NET MVC中设置默认JSON序列化程序

C# 在ASP.NET MVC中设置默认JSON序列化程序,c#,asp.net-mvc,asp.net-mvc-4,json.net,C#,Asp.net Mvc,Asp.net Mvc 4,Json.net,我正在开发一个已经部分转换为MVC的现有应用程序。每当控制器响应JSON ActionResult时,枚举将作为与字符串名称相反的数字发送。听起来默认序列化程序应该是JSON.Net,它应该将枚举作为其名称而不是整数表示发送过来,但这里的情况并非如此 我是否缺少将其设置为默认序列化程序的web.config设置?或者还有其他需要更改的设置吗?在ASP.Net MVC4中,JsonResult类中使用的默认JavaScript序列化程序仍然是(您可以在 我认为您已经将它与ASP.NETWeb.AP

我正在开发一个已经部分转换为MVC的现有应用程序。每当控制器响应JSON ActionResult时,枚举将作为与字符串名称相反的数字发送。听起来默认序列化程序应该是JSON.Net,它应该将枚举作为其名称而不是整数表示发送过来,但这里的情况并非如此


我是否缺少将其设置为默认序列化程序的web.config设置?或者还有其他需要更改的设置吗?

在ASP.Net MVC4中,
JsonResult
类中使用的默认JavaScript序列化程序仍然是(您可以在

我认为您已经将它与ASP.NETWeb.API混淆了,在ASP.NETWeb.API中,JSON.Net是默认的JS序列化程序,但MVC4没有使用它

因此,您需要配置JSON.Net以使用MVC4(基本上您需要创建自己的
JsonNetResult
),关于它的文章很多:

如果您还希望将JSON.Net用于控制器操作参数,那么在模型绑定期间,您需要编写自己的
ValueProviderFactory
实现

您需要向以下机构注册您的实施:

ValueProviderFactories.Factories
    .Remove(ValueProviderFactories.Factories
                                  .OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
valueProviderFactorys.Factories
.删除(ValueProviderFactorys.Factorys)
.OfType().Single());
valueProviderFactorys.Factories.Add(新的MyJsonValueProviderFactory());

您可以使用内置的
JsonValueProviderFactory
作为示例或本文:

ASP.NET MVC 5修复程序:

我还没有准备好更改为Json.NET,就我而言,错误发生在请求过程中。在我的场景中,最好的方法是修改实际的
JsonValueProviderFactory
,它将修复应用于全局项目,并且可以通过编辑
global.cs
文件来完成

JsonValueProviderConfig.Config(ValueProviderFactories.Factories);
添加web.config条目:

<add key="aspnet:MaxJsonLength" value="20971520" />

这有助于发送JSON响应,但在框架尝试将传入调用映射到传递到操作方法中的参数时,对传入JSON进行反序列化则没有帮助。如何更改MVC为此使用的序列化程序?如果要将Json.NET用于传入参数,则需要编写自己的
ValueProviderFactory
实现。您可以使用内置的
JsonValueProviderFactory
作为示例。您需要将实现注册到:
valueProviderFactorys.Factories.Remove(valueProviderFactorys.Factories.OfType().Single());valueProviderFactorys.Factories.Add(新的MyJsonValueProviderFactory())。另请参见:@Marc根据源代码:MVC5中的
JsonResult
仍然使用旧的
JavaScriptSerializer
,并且不使用JSON。net@jpgrassiOfType
是在
System.Linq
命名空间中定义的扩展方法。你有使用System.Linq的
在您的cs文件中?作为记录,MVC6最终使用Json.NET作为默认值。在我们的应用程序中添加了这两个类,并且成功了。非常感谢,伙计,您为我们节省了很多时间和麻烦。if(num>\u maximumDepth)中的错误消息中有一个错误。它不是MaxJsonLength,而是MaxJsonDeserializerMembers属性。你的代码救了我
public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}
public class CustomJsonValueProviderFactory : ValueProviderFactory
{

    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return null;

        Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);

        return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
    }

    private static object GetDeserializedObject(ControllerContext controllerContext)
    {
        if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            return null;

        string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
        if (string.IsNullOrEmpty(fullStreamString))
            return null;

        var serializer = new JavaScriptSerializer()
        {
            MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
        };
        return serializer.DeserializeObject(fullStreamString);
    }

    private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> strs = value as IDictionary<string, object>;
        if (strs != null)
        {
            foreach (KeyValuePair<string, object> 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<string, object> _innerDictionary;

        private int _itemCount;

        static EntryLimitedDictionary()
        {
            _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
        }

        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }

        public void Add(string key, object value)
        {
            int num = this._itemCount + 1;
            this._itemCount = num;
            if (num > _maximumDepth)
            {
                throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
            }
            this._innerDictionary.Add(key, value);
        }
    }

    private static string MakeArrayKey(string prefix, int index)
    {
        return string.Concat(prefix, "[", index.ToString(CultureInfo.InvariantCulture), "]");
    }

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (string.IsNullOrEmpty(prefix))
        {
            return propertyName;
        }
        return string.Concat(prefix, ".", propertyName);
    }

    private static int GetMaximumDepth()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] 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)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }
}