Error thrown while performing ajax call to web api - c#

I have the following basic code. I tried to debug this code but the javascript is very painful to debug, and I do not know where it is failing:
jQuery.support.cors = true;
var packet = {
Image: imageAsString,
PhnType: phoneType,
PhnMdl: phoneManufacturer
};
$.ajax({
url: "https://molecheckerservices2.azurewebsites.net/api/Testing/SubmitTestingData",
type: "POST",
dataType: "json",
data: JSON.stringify({ packet }),
success: function(data, textStatus, xhr) {
alert('yes');
window.localStorage.setItem("dataObject", JSON.stringify(data));
window.location = "results.html";
},
error: function (xhr, textStatus, errorThrown) {
alert('no');
window.localStorage.setItem("dataObject", JSON.stringify([.33, .33, .33]));
window.location = "results.html";
}
it gives me back an alert no, which corresponds with a failure. Additionally as I debug I see in my Javascript console that the error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
Pops up. I tried to look up what this mean but I would be incredibly grateful for any problem specific advice!

Open up Fiddler and manually POST to your endpoint. If you do that, you will see the same error message I saw:
{"message":"No API version was specified in the request, this request needs to specify a ZUMO-API-VERSION of '2.0.0'. For more information and supported clients see: http://go.microsoft.com/fwlink/?LinkId=690568#2.0.0"}
It has a handy-dandy link in there for you. Also, here is a SO answer that possibly applies to you.
I did add the header mentioned above, resent the request and I received that sweet 200 response from your service, so I'm pretty sure that's your issue.
P.S. If you don't want random strangers inserting data into your app like I just did, you should secure your service or at least obfuscate the URL when mentioning it in public.

Related

How to view soap service data from my browser

I'm completely new to how soap services work, please correct me if my understanding is wrong. I would like to pass parameters and call a function from a soap service by typing in a url on my browser (Chrome) and then would like to see the results. I tried searching and following the information from here, but I'm not sure what I'm doing wrong. I have tried the following variations:
http://<servername>/apppath/MyService.asmx?op=GetData?loc=01&status=OPEN
http://<servername>/apppath/MyService.asmx/GetData?loc=01&status=OPEN
This is what I get when I go to the url.
http:/<servername>/apppath/MyService.asmx?op=GetData?
Please help.
Maybe you are requesting wrong urls? If you have .asmx in your application - you should be able to see the description page on the url
http://{servername}/{apppath}/MyService.asmx
Of course you should replace {servername} the {apppath} with your values.
You have to send an HTTP POST request in order to call your web service GetData.
Your JS code should be something like:
//url should be MyService.asmx/GetData
function callWS(url) {
var loc = "01";
var status = "OPEN";
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: JSON.stringify({ loc: loc, status: status }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { alert(response); }
};
$.ajax(options);
}
So the error was my understanding of SOAP and host to use Postman. In short, I wasn't able to accomplish a SOAP request through the browser. Also, the picture supplied, it showed I was missing 2 things. 1) The SoapAction 2) The parameters were not supplied in the url but rather in the <soap:Body> tag. These were supplied in the POST and I was able to view my results in Postman

asp.net api service.svc query length problems

Hello I got a service that is made for sending html mails, it will be called from a method "SendMail(data) about 1500 characters.
I access the service though JQuery with AJAX call and JSON:
var data = encodeURIComponent(JSON.stringify(dataArray));
$.ajax({
type: "GET",
url: "http://localhost:53334/Service.svc/SendMail?data=" + data,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function () {
alert("Reklamationen er blevet sendt!");
},
error: function (err) {
alert("Kunne ikke sende reklamation! Der opstod en fejl.");
}
});
I got alot of fields and if I fill everything out it gives a 404 not found response but then if I leave some random fields empty it gets to the API and executes the method it should? So I think its about the data size. I have tried many settings in webconfig but i havent managed to find a solution.
I hope there will be someone who can help me.
You should really be using POST as indicated by Tikkes. Semantically you aren't requesting a resource from the server, so GET doesn't make sense. Also, as noted here there is a maximum length that is enforced for Urls which is what GET uses to pass params(as you can see in your code as well). POST on the other hand uses the request body to send its data. Also, as noted here POST and GET sizes are usually configurable on the server, but POST is generally much larger(2KB vs 10MB defaults) as stated in one of the answers. Hope this helps.

AJAX requests from jquery in android application to WCF Service always fails

I have an application where I fetch a list of requests made by the user based on the idNo provided. The android application uses AJAX to make a request to a .NET WCF Service which in turn returns a IEnumerable of DTO for that request.
Following is the AJAX Code:
$.ajax({
url: baseURL + "RequestStatusList/"+idNo,
cache : false,
type : "GET",
dataType : "json",
contentType : "application/json; charset=utf-8",
crossdomain : true,
success : function(data, tst, xhr) {
//do something here
},
error: function (xhr, tst, err) {
alert(' Please Try Again ' + xhr.status);
}
});
A similar piece of code works in another page in the application, where only the process in success is different, rest all is same.
Here every time the request fails and enters the error section and displays undefined/0 as error. No details about error, hence i cannot get what maybe the problem.
When I debug the server side code I get proper value in the parameter passed and a IEnumerable is formed and returned. What fails is the client side code after successful execution of server code.
Please Help.
Thanks in advance.

JQuery Ajax Getting Response, but Always invoking Error function JSONP

I have a HttpListenerContext class, that always listen to port 13001. when ever an ajax call comes I am passing data as follows
context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);
Next I am invoking that Server by using Jquery ajax as follows
$.ajax({
url: "http://localhost:<13001>/hit/number',
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonp: "jsonp",
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error");
}
});
Ajax Get Request getting Success, I am able to see the response in Chrome Network->Response Tab as follows
"jsonp({"Status":"Good"})"
But I can't get this message in Ajax Success function. It's always displaying error. Can any one please tell me where I did mistake.
Response Headers
Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:23
Content-Type:application/javascript
Date:Fri, 27 Sep 2013 01:12:25 GMT
Server:Microsoft-HTTPAPI/2.0
My gut tells me that you are not passing back a full HttpResponse. You are just passing back a text string. Since it isn't a valid HttpResponse jQuery is going to think it failed.
Solution: try adding context.Response.StatusCode = 200; this before you send the response. You might need to add a content-type as well to the response.
context.Response.StatusCode = 200;
context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);
Same issue I have faced with oData service, its fixed by by adding the "$callback" keyword by end of the url.
So the ajax URL will be like
https://example.com/ApplicationData.svc/Products?$format=json&$callback=?
courtesy :http://www.kendoui.com/blogs/teamblog/posts/11-08-24/cross-domain_queries_to_odata_services_with_jquery.aspx

Dojo 1.8 web service call fails with status: 500 error code

dojo.xhrPost({
url: "Default.aspx/TestMethod",
handleAs: "json",
contentType: "application/json",
postData: dojo.toJson({ }),
load: function (result) {
debugger;
},
error: function (err) {
debugger;
}
});
That is the script I use to make a request to a WebMethod that is exposed in Default.aspx. The method is called TestMethod.
The error that I get is:
Unable to load Default.aspx/TestMethod status: 500
If you need any additional information please let me know.
*Note : I can call the method from the server side and it returns the results as intended.
I've been there. :(
Usually it is a problem with the format of the data that you are passing in. For instance, if your WebMethod has a parameter that is an int and you are passing a string, you will get a failure like this.
I would use a tool like Fiddler http://www.fiddler2.com/fiddler2/ to see what you are sending to the method.
Also turn on what ever server side logging and tracing that you have and use it. One source that is useful for 500 errors (which tend to happen before "your" server code is reached) is Asp.net health monitoring.
There is more info about setting that up and using it at http://msdn.microsoft.com/en-us/library/bb398933(v=vs.100).aspx

Categories

Resources