pessi pessi - 3 years ago 206
ASP.NET (C#) Question

ASP.NET WebMethod reading file error

Have a simple WebMethod that reads a text file (500000 lines) into a string array.
The ajax calling the method has success and error calls.

I can debug on backend code and see that everything is as expected. All values are read as intended and code proceeds to the end correctly.

HOWEVER, when the code proceeds beyond the

line, it tiggers an error on the front end.

What exactly happens:

  • I put a breakpoint on 1st line of c# code where I read the text file.

  • When I go to next line during debugging, the
    array has all the words that are read from the file. There is no error. However, the webpage (frontend) triggers alert(error).

Cannot figure out what is wrong.

C# WebMethod:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string[] Test(string Test)
string[] mywords = File.ReadAllLines(Server.MapPath("~/Sample/sample.txt"));
return mywords;

AJAX call:

type: "POST",
url: "test.aspx/Test",
data: JSON.stringify({ Test: Test }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
error: function (xhr, status, error) {

UPDATE: When I change the input file to another one that contain fewer lines like 10,000 lines. It works without errors.

Answer Source

There's a default maximum length of JSON string of 2097152 characters (4 MB). It's defined in the MaxJsonLength property in the Web.config.

You probably need to define a higher value in your config. Here is the maximum value you can set for the MaxJsonLength:

            <jsonSerialization maxJsonLength="2147483647"></jsonSerialization>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download