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

查看:68
本文介绍了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.我曾尝试将上述内容单独放置在根或区域的 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

这是我要针对其发布的方法:

Here is the method that I am wanting to POST against:

[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天全站免登陆