Ajax results in 500 Internal Server Error because of large JSON - c#

I have a the following code
ajax call
$.ajax({
type: "POST",
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
url: "Account/SomeFunc",
data: JSON.stringify(dataToSend),
success: function (res) {
//some code
},
error: function (res, textStatus, errorThrown) {
//some code
}
});
and on the server-side
public ActionResult SomeFunc()
{
//some code
VeryBigObject result = getResult();
if (result == null)
return null;
var jsonResult = Json(result, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
result variable can be small but sometimes its a very big object. when the object is small enough the code works and the ajax success code is activated but when the result is big enough the code fails with 500 Internal Server Error.
I cant put MaxJsonLength any bigger because its an int but sometimes I need to send some big data.. what can I do?

Use the code below in web.config. It will solve your problem.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="900000" />
</webServices>
</scripting>
</system.web.extensions>

Increasing maxJsonLength in Web config worked for me when I faced similar issues with large json data.

Related

Max Length for Json Object Asp.net Core 3.1

Although this is queried around 2 years ago, but I'm still facing the issue and there is no way to get out of it without. Is there any way to set Max size for JSON object in Asp.net Core 3.1? There are ways to do this in other .Net frameworks except .Net core (or may I ain't found it yet).
How to Set Max Json Length in .net core
I'm having JSON object array of length around 3k, same file with around 20 objects works fine but as I increase the size the data goes null in controller method (Even while inspecting in DOM, console.log show the exact array of object).
console.log(candidate_List);
$.ajax({
url: '#Url.Action("Insert_Candidates")',
data: { "selected_list": candidate_List },
type: "POST",
dataType: "json",
async: true,
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert("fail");
}
});
[HttpPost]
public async Task<IActionResult> Insert_Candidates([FromForm]List<CandidateDTO> selected_list)
{
string result = "";
if (ModelState.IsValid)
{
}
}
Thanks to all those who helped me, I'm putting my words with solution. I've added the following thing in my code and achieved the target.
$.ajax({
url: '#Url.Action("Insert_Candidates")',
data: { "selected_list": candidate_List},
type: "POST",
dataType: "json",
async: true,
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert("fail");
}
});
Controller's Method here
[HttpPost]
[RequestFormLimits(ValueCountLimit = int.MaxValue)]
public async Task<IActionResult> Insert_Candidates([FromForm]List<RecuritementDTO> selected_list)
{
string result = "";
if (ModelState.IsValid)
{
try
{
result = count + " rows has been saved";
}
catch (Exception ex)
{
//throw;
string message = ex.ToString();
result = ex.Message.ToString();
}
}
return Json(new { d = result });
}
Startus.cs here
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = 10; //default 1024
options.ValueLengthLimit = int.MaxValue; //not recommended value
options.MultipartBodyLengthLimit = long.MaxValue; //not recommended value
options.MemoryBufferThreshold = Int32.MaxValue;
});
services.AddMvc(options =>
{
options.MaxModelBindingCollectionSize = int.MaxValue;
});
Here goes Webconfig code (I've added this too... may be it helped me to cross the bridge)
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
This is all I've made change to my code and I've made it. I hope this code might help our stack team members.
Cheers :)

Saving HTML 5 Canvas via Ajax ASP.NET

I'm trying to sand canvas Data to web service via Ajax, but I get an error:
500 (Internal Server Error)
JavaScript:
var imageData = canvas.toDataURL("image/png");
imageData = imageData.replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: "WebService.asmx/SendRegistration",
data: "{ 'imageData':'" + imageData + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded
});
Web service:
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public bool SendRegistration(string imageData)
{
....
}
When the data is a string it must be a query string. Don't use string, simply use an object and jQuery will convert it for you:
data: { imageData: imageData },
If you really want to make the string by yourself, use:
data: "imageData=" + imageData",
Remember, it's a query string, so the format is x=1&y=2&z=3.
The problem was solved, I had to add this code due to a huge file.
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>

calling webservice POST method from HTML page using ajax?500 internal server error

my html page code is this
function Save_Click() {
if (validate() == true)
{
var dr = {};
dr.phoneNo = phoneNo;
dr.mobileNo = mobileNo;
dr.Adress = Adress;
dr.dob = dob;
var Record = JSON.stringify(dr);
$.ajax({
type: "POST",
url: "doctorRecord.asmx/Save_Update_Doctor",
data: Record,
contentType: "application/json",
dataType: "json",
success: function (data) {
alert("successfully saved");
},
error: function (result) {
//alert("Error login");
}
});
}
};
my webservice.asmx code is
[WebMethod]
public object Save_Update_Doctor(Doctor_Business.Model.Doctor info)
{
//code here
return "something"
}
my JSON Data POST is
"{"phoneNo":"jsmith","mobileNo":"AC101","Adress":"2817 S 49th\nApt 314\nSan Jose, CA 95101","dob":"24-01-2016"}"
the error is
Request format is unrecognized for URL unexpectedly ending in '/Save_Update_Doctor'.
http://localhost:62730/Forms/Theme/doctorRecord.asmx/Save_Update_Doctor
500 (Internal Server Error)
I TESTED THE WEBSERVICE USING TEST MODE BUT RUN SUCESSFULL BUT WHEN I TRIED TO CALL FROM HTML page any WEB METHOD IS .cs Class return 403 request forbiddenn and webservice always return internal server 500
what is wrong i have this web.config file what changes or code should i add kindly check the above code and tell?
<?xml version="1.0" ?>
working web service url
localhost:62730/Forms/Theme/doctorRecord.asmx?op=Save_Update_Doctor
and url to be used is this
localhost:62730/Forms/Theme/doctorRecord.asmx/Save_Update_Doctor
Add following configuration element in web.config inside <system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Update
One more important thing. In order for the asmx script to be accessible from the client side, we need to include
[ScriptService]
Don't stringify your data in the ajax call, since jQuery does it for you. Here, you send a string to the server, not a json object.
$.ajax({
type: "POST",
url: "doctorRecord.asmx/Save_Update_Doctor",
data: Record,
success: function(data) {
alert("successfully saved");
},
error: function(result) {
//alert("Error login");
}
});
Also, your webservice seems strange. You method should receive an object of Class XX with properties phoneNo, mobileNo, etc.
public class Infos
{
public string phoneNo = {get; set; };
public string mobileNo = {get; set; };
// ...
}
[WebMethod]
public string Save_Update_Doctor(Infos infos)
{
// ...
}

jQuery POST passing null string on server (ASP.NET)

I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.
var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();
Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.

Error 500 using C# WebMethod from jQuery ajax

I keep getting error 500 from my ajax function when trying to call WebMethod.
$.ajax({
type: "POST",
url: "BookingCalendar.aspx/TestFunction",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function () {
alert("Error");
}
});
[WebMethod]
public static string TestFunction()
{
return DateTime.Now.ToString();
}
After more looking I found out that GET and POST are disabled by default in .NET. I added this to the web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
For more information look here.

Categories