MVC 5增加POST请求中的最大JSON长度 [英] MVC 5 Increase Max JSON Length in POST Request

查看:481
本文介绍了MVC 5增加POST请求中的最大JSON长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向主体中具有大量JSON数据的MVC控制器发送POST请求,并抛出以下错误:

I am sending a POST request to an MVC controller with a large amount of JSON data in the body and it is throwing the following:

ArgumentException:使用进行序列化或反序列化时出错 JSON JavaScriptSerializer.字符串的长度超过 在maxJsonLength属性上设置的值. 参数名称:输入

ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Parameter name: input

为解决这个问题,我尝试了许多Web.Config解决方案.即:

To remedy this, I have tried a number of Web.Config solutions. Namely:

<system.web> 
...
<httpRuntime maxRequestLength="2147483647" />
</system.web>

...

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="2147483644"/>
    </webServices>
  </scripting>
</system.web.extensions>

现在,我正在与之通信的控制器位于其自己的区域中,具有自己的Web.Config.我曾尝试将以上内容分别放在根目录或Area的Web.Config中,但都无法正常工作.当我在同一控制器中使用其他方法进行调试时,将获得带有以下内容的默认JSON最大长度:

Now, the controller that I am communicating with is in its own Area, with its own Web.Config. I have tried placing the above in either the root or the Area's Web.Config individually, but neither are working. When I debug on a different method within the same controller, I get the default JSON Max Length with the following:

Console.WriteLine(new ScriptingJsonSerializationSection().MaxJsonLength);
// 102400

这是我要针对的方法:

[HttpPost]
public JsonResult MyMethod (string data = "") { //... }

如何增加MVC控制器的最大JSON长度,以便我的请求可以成功到达该方法?

How can I increase the Max JSON Length for the MVC Controller so that my request can successfully reach the method?

添加了<httpRuntime maxRequestLength="2147483647" />

推荐答案

因此,尽管这是一个不太令人满意的解决方案,但我还是通过手动读取请求流而不是依靠MVC的模型绑定器解决了这个问题.

So, although this is a rather disagreeable solution, I got around the problem by reading the request stream manually, rather than relying on MVC's model binders.

例如,我的方法

[HttpPost]
public JsonResult MyMethod (string data = "") { //... }

蜜饯

[HttpPost]
public JsonResult MyMethod () {
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();
    MyModel model = JsonConvert.DeserializeObject<MyModel>(json);
    // use model...
}

这样,我可以使用JSON.NET并通过MVC的默认反序列化器解决JSON最大长度限制.

This way I could use JSON.NET and get around the JSON max length restrictions with MVC's default deserializer.

为适应该解决方案,我建议创建一个自定义的JsonResult工厂,该工厂将替换Application_Start()中的旧工厂.

To adapt this solution, I would recommend creating a custom JsonResult factory that will replace the old in Application_Start().

这篇关于MVC 5增加POST请求中的最大JSON长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆