首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在ASP.NET MVC中设置默认的JSON序列化程序

在ASP.NET MVC中设置默认的JSON序列化程序
EN

Stack Overflow用户
提问于 2013-01-30 04:35:43
回答 2查看 62.2K关注 0票数 59

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-30 04:47:40

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

我认为您将其与ASP.Net Web.API混淆了,其中JSON.Net是默认的JS序列化程序,但MVC4不使用它。

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

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

并且您需要向以下位置注册您的实现:

代码语言:javascript
复制
ValueProviderFactories.Factories
    .Remove(ValueProviderFactories.Factories
                                  .OfType<JsonValueProviderFactory>().Single());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());

您可以使用内置的JsonValueProviderFactory作为示例,或者阅读本文:ASP.NET MVC 3 – Improved JsonValueProviderFactory using Json.Net

票数 73
EN

Stack Overflow用户

发布于 2018-06-03 19:08:30

ASP.NET MVC 5修复:

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

代码语言:javascript
复制
JsonValueProviderConfig.Config(ValueProviderFactories.Factories);

添加web.config条目:

代码语言:javascript
复制
<add key="aspnet:MaxJsonLength" value="20971520" />

然后创建以下两个类

代码语言:javascript
复制
public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}

这基本上是System.Web.Mvc中默认实现的精确副本,但增加了一个可配置的web.config应用设置值aspnet:MaxJsonLength

代码语言:javascript
复制
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;
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14591750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档