[英]JsonMaxLength exception on deserializing large json objects
介绍:
Web应用程序,ASP.NET MVC 3,一种控制器操作,它接受具有(可能)大字段的POCO模型类的实例。
型号类:
public class View
{
[Required]
[RegularExpression(...)]
public object name { get; set; }
public object details { get; set; }
public object content { get; set; } // the problem field
}
控制器动作:
[ActionName(...)]
[Authorize(...)]
[HttpPost]
public ActionResult CreateView(View view)
{
if (!ModelState.IsValid) { return /*some ActionResult here*/;}
... //do other stuff, create object in db etc. return valid result
}
问题:
一个动作应该能够接受大型JSON对象(在单个请求中至少高达100兆字节,这不是一个笑话)。 默认情况下,我遇到了一些限制,如httpRuntime maxRequestLength
等。除了MaxJsonLengh之外,所有限制都解决了 - 这意味着JSON的默认ValueProviderFactory无法处理这些对象。
尝试:
设置
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
按照@ Darin的答案中的描述创建我自己的自定义ValueProviderFactory:
JsonValueProviderFactory抛出“请求太大”
Dictionary<String,Object>
,但这不是我想要的 - 我想将它反序列化为我可爱的POCO对象并将它们用作动作的输入参数。 所以,问题:
有谁能建议一个好的解决方案?
内置的JsonValueProviderFactory忽略<jsonSerialization maxJsonLength="50000000"/>
设置。 因此,您可以使用内置实现编写自定义工厂:
public sealed class MyJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 2147483647;
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
与默认工厂相比,我做的唯一修改是添加以下行:
serializer.MaxJsonLength = 2147483647;
不幸的是,这个工厂根本不可扩展,密封的东西,所以我不得不重新创建它。
并在您的Application_Start
:
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<System.Web.Mvc.JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory());
我发现maxRequestLength并没有解决问题。 我用以下设置解决了我的问题。 它比必须实现自定义ValueProviderFactory更清晰
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
信用可归结为以下问题:
JsonValueProviderFactory抛出“请求太大”
此设置显然与高度复杂的json模型有关,而与实际大小无关。
Darin Dimitrov的解决方案对我有用,但我需要在读取之前重置请求流的位置,添加以下行:
controllerContext.HttpContext.Request.InputStream.Position = 0;
所以现在,方法GetDeserializedObject如下所示:
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
controllerContext.HttpContext.Request.InputStream.Position = 0;
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 2147483647;
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.