AJAX post returns always 500, cant debug - c#

Recently I was faced with some strange server behavior - it started to return a 500 error at several ajax POST requests. All was working fine before. GET requests work fine. I have made Visual Studio trace my code exceptions but I still cannot see requests coming in while debugging. Do you have any ideas?
Example
$.ajax({
type: "POST",
url: "/home/some-action",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
}
});
[POST("some-action")]
public ActionResult SomeAction()
{
return new JsonNetResult("success request");
}
Update
I use this prefix for my controller:
[RoutePrefix("home")]

So you're using Attribute Routing?
I can't see your Controller but I assume you're missing the Route for /home in the controller, or removed it from [POST("/home/some-action")]
We need more information though. Current assumption is the URL doesn't exist.

Related

Http request Unauthorized

I am developing my first web app using angularjs , created a aspx page , added the controller. When I debug in local ASPX page is getting opened and Controller also working fine , but when I call the save function in angular . It is returning the status code as not authorized .
below is the call i have made
$http({
method: "POST",
url: "Login.aspx/SaveOrganizationName",
dataType: 'json',
data: { },
headers: { "Content-Type": "application/json" }
}).
Any suggestion, how to fix ?? I have set the project to run on IIS. as I'm not having enough idea on this , please explain me detailed
thanks

Why is this jquery ajax GET call to a C# method not working?

I have a C# .NET MVC 5 project. I'm trying to submit a GET request from ajax to a controller method on the server. The problem is that, even though this jquery is being called, the GET always returns a 404. Here is the js:
var theArguments = { "prefix": prefix, "level": level, "number": number };
$.ajax({
url: "GetMasteryObjective",
type: "GET",
data: theArguments,
//data: JSON.stringify({ prefix: "prefix", level: "level", number: "number" }),
//url: "/MasteryObjectiveAPI/GetMasteryObjective?prefix=" + prefix + "&level=" + level + "&number=" + number,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Successfully queried the database to validate the given mastery objective.");
},
error: function () {
console.log("There was an error with trying to validate the mastery objective with the database.");
}
});
As you can see I've tried several variants of how the variables are submitted (commented out). This is the controller method that is never getting hit.
[HttpGet]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MasteryObjective GetMasteryObjective(String prefix, String level, String number)
{
//code here
}
Other methods in the same controller have no problem being posted to. So maybe there's something I don't understand about GET? I understand that it should be valid to submit variables with a GET request.
Wow. I just discovered the answer to my own question while creating this post. I needed to remove static from my controller method.
Happy that, you have got the solution.
However, thinking that this may help others .....
One of the reason for ajax call not hitting the Method in controller is:
If the controller method is under [Authorize] but the user is trying to hit without logging in.
Solution: If want to allow unauthorized access to that method; mark that method has [AllowAnonymous], otherwise log-in and then try.

Unknown web method. Parameter name: methodName

In researching this problem most SO issues were about the static method as a fix.
Since it's not working with the real (and a bit sophisticated) WebMethod I've just created a simple one for the sake of checking if reaching the method itself is possible.
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string HelloWorld()
{
return "Hello World!";
}
The call.
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
});
</script>
It always comes down to 500 (Internal Server Error)
Unknown web method HelloWorld.
Parameter name: methodName
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method HelloWorld.
Parameter name: methodName
Why is this failing?
I had this issue as well, but slightly differently I had this method in a .asmx file and so ran across the "static" issue, but in a different way.
If you have a method as part of your Page class, it must be static.
If you've put a method in an .asmx file to use across several pages, it must not be static.
I had a problem in the actual .aspx file, the line
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.xxx.cs" Inherits="xxx.xxx" %>
wasn't present in the code. How did it get changed? I Don't know :(.
For me, the primary issues was to change javascript post to pass in no arguments such as
$http.post("Status.aspx/MyData", {})
Then to verify nothing was cached, I then deleted [System.Web.Services.WebMethod] in the code behind file above public static string MyData(). Then I built the project to failure, then re-added the aformentioned deleted attribute and built to success.
Upon running it worked.
Missing the [WebMethod] above your server side function will also cause this error.
To be honest, I've just realised "again" how tired we could be in some cases.
For me it was just a private method instead of a public one.
In my case there was a problem in the URL, it was a Asp.Net Website application:
For ex:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld", <----- Here
dataType: "json",
success: function (data) {
alert(data.d);
}
});
My usersWebMethods.aspx in inside UI (Custom Created) folder so If I put URL as usersWebMethods.aspx/HelloWorld it does not work but when I added leading / to it then ajax method called properly!
Changed from:
usersWebMethods.aspx/HelloWorld
To
/usersWebMethods.aspx/HelloWorld --
I run into this exact problem in ASP.net(framework/web forms) with JS using webservice and I solved it by removing the static key word from the method declaration
[WebMethod]
public List<ViewModel> GetAirLines()
{
//Code goes here
}
instead of
[WebMethod]
public static List<ViewModel> GetAirLines()
{
//Code goes here
}

Jquery call to Controller of MVC: ReferenceError: url is not defined

I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?

WCF service - HTTP500

I need help with wcf service. i have a ajax-enabled wcf service:
public class AddFavorites : Page
{
// Add [WebGet] attribute to use HTTP GET
[WebGet(RequestFormat = WebMessageFormat.Json)]
[OperationContract]
public void AddFavorite()
{
this.AddMyFavorite(10, "sometext", "sometext");
}
}
And clientside looks like this:
function AddFavorite() {
$.ajax({
type: "GET",
url: "/WebServices/AddFavorites.svc/AddFavorite",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
});
};
Im using fiddler to trace the application and i always get HTTP500. The class is inherited from Page class and uses the AddMyFavorite method that takes care of database. Website is hosted on iis7
An HTTP 500 error is something bad that happened on the server. Go in debug mode and debug your service - you'll see a more descriptive message about what went wrong. I would guess that the AddMyFavorite method throws and exception of some kind, but you have to debug this to see for sure.
Is there anything returned in 'Textview' in fiddler? You can see the actual error returned in firebug net panel.

Categories

Resources