Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

c# - MVC 5 Increase Max JSON Length in POST Request

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: 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

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>

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 = "") { //... }

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

Edit: Added <httpRuntime maxRequestLength="2147483647" />

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For example, my method

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

Became

[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...
}

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...