Error 500 using C# WebMethod from jQuery ajax - c#

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.

Related

AJAX Post Test Method Failed to load resource

I created a test web application that is calling my MVC application. I can call the POST fine with Postman and wanted to try and call it from a web browser but I am getting a 405 error. ANy help would be great.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Test HTML Project
$.ajax({
type: "POST",
url: "URL",
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(json));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
MVC Application
public class PublicController : ApiController
{
[System.Web.Http.HttpPost]
public IHttpActionResult MethodTest(string key, string action)
{
}
}
web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
you have to fix your ajax.remove headers and contenttype and fix dataType and add data
$.ajax({
type: "POST",
url: "http://localhost:60876/WebApi/public/SkipAuthenticationAndLogin"
data:{
key:"key",
userName:"name",
succesUrl:"url"
},
dataType: "json",
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(response));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
and remove post from action
public IHttpActionResult MethodTest(string key, string userName, string successUrl)
{
}

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>

Unable to send large data in Jquery ajax call

Hi I am developing MVC4 application. I am saving values to Database. I am getting below error.
The request filtering module is configured to deny a request where the query string is too long.
I am making ajax call and sending data as Json as below.
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc?JsonValue=' + JSON.stringify(SaveUpload) + '&gridData=' + strOrderArr,
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});
Web.config
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
May i know am i following good approach to handle above scenario when posting huge data to database? Thanks in advance.
It's a POST Request yet you're passing data in Query string!
Pass data in Data parameter:
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc',
data: JSON.stringify({ JsonValue: SaveUpload, gridData:strOrderArr }),
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});

Ajax results in 500 Internal Server Error because of large JSON

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.

Authentication failed error when calling web method using $.ajax

When I make a JQuery call, I get an Authentication failed response:
{
Message: "Authentication failed.",
StackTrace: null,
ExceptionType: "System.InvalidOperationException"
}
jQuery call:
$(document).ready(function () {
//Handle the change event for the drop down list
$("#ddRegions").change(function () {
//create the ajax request
$.ajax({
type: "POST", //HTTP method
url: '<%= ResolveUrl("WebForm2.aspx/getLocations")%>', //page/method name
data: "{}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
alert(msg.toSource());
}
});
});
});
The web method:
public static string getLocations() {
System.Diagnostics.Debug.WriteLine("Getting Locations.");
return "{region:auckland, city:auckland}";
}
I added the following to my web.config:
<authorization>
<allow users="*" />
</authorization>
<authentication mode="None" />
And I tried setting the AutoRedirectMode to Off in RouteConfig.cs. This stops the error, but still the web method never gets called. Any suggestions?
Resolved by setting AutoDirectMode to Off in App_Start/RouteConfig.cs
settings.AutoRedirectMode = RedirectMode.Off;
and adding a ScriptManager to the aspx page that has an EnablePageMethods set to 'true':
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

Categories