XHR statusText not being set - asp.net

What would cause the XHR to get overriden? I'm assuming that's what's happening here.
I am setting the status and code, show here, with a helper class:
if (program.Name == programName)
{
ServiceHelper.SetHttpError(501, "'Program Name' Already Exists.'");
return;
}
class:
public static void SetHttpError(int statusCode, string message)
{
HttpContext.Current.Response.StatusCode = statusCode;
HttpContext.Current.Response.StatusDescription = message;
}
handling the xhr:
function CallService(method, jsonParameters, successCallback, errorCallback)
{
if (errorCallback == undefined)
{
errorCallback = function(xhr) {
if (xhr.status == 501) {
alert(xhr.statusText);
}
else {
alert("Unexpected Error");
}
}
}
$.ajax({
type: "POST",
url: method,
data: jsonParameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successCallback,
error: errorCallback
});
}
At one time this was working.. now all that the alert shows is "error" not the message I'm providing..
Any idea?

What version of jQuery are you using? The latest docs say that the signature of the error callback is:
error(jqXHR, textStatus, errorThrown)
Your message might be in the textStatus argument.
Have you tried using FireBug to break on the error function and look at the properties of the xhr object?

I came just accross a similar issue where this statusText was not set, but only when using HTTPS on IIS, whereas it would work on on plain HTTP. I eventually found that IIS only supports HTTP2 on TLS, and in HTTP2 there is no status code description anymore.
When I used Fiddler to troubleshoot, it worked in both http and https, probably because of this !
In ASP.NET MVC you just can't use HttpStatusCode(code,description) anymore because the description will go nowhere. You have to pass the description e.g. into the response body instead. Or disable HTTP2 for the time being.

Related

CORS Issue same controller, one method is ok, other one is not

Very strange error I'm experiencing.
I have two methods in controller which are called by angular js http get event.
First one works fine, second one is throwing CORS error, not sure how is that possible since both of them are in same controller.
This is the error I'm getting:
These are the calls I'm doing in angularjs:
$http({
url: 'http://localhost:52876/api/Admin/GetLoanInfo',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
$scope.LoanDetailsVM.LoanStatus = data.LoanStatus;
}).error(function (data, status) {
console.log(data);
});
$http({
url: 'http://localhost:52876/api/Admin/GetLoanCovenants',
method: "GET",
params: { loanID: querystringParam }
}).success(function (data, status) {
console.log(data);
}).error(function (data, status) {
console.log(data);
});
And the controller methods:
[HttpGet]
[Route("api/Admin/GetLoanInfo")]
public async Task<IHttpActionResult> GetLoanInfo(int loanID)
{
LoanApplication newApplication = null;
newApplication = db.LoanApplications.FirstOrDefault(s => s.LoanId == loanID);
return Ok(newApplication);
}
[HttpGet]
[Route("api/Admin/GetLoanCovenants")]
public async Task<IHttpActionResult> GetLoanCovenants(int loanID)
{
LoanCovenant newCovenant = null;
newCovenant = db.LoanCovenants.FirstOrDefault(s => s.LoanID == loanID);
return Ok(newCovenant);
}
I'm able to hit both methods, I have breakpoints in both of the methods, but not sure why is complaining about CORS on the first one.
Calling methods using CORS from a Web browser makes Web API being called first with an OPTIONS request (example at the end of this article).
This way, the browser knows if it can call the requested API.
In your case, the call to your endpoint seems to be crashing, which means the HTTP 500 error does not contain any CORS headers.
This explains why the web browser complaning about CORS HTTP Header missing: Reason: CORS Header 'Access-Control-Allow-Origin' missing.
If you fix your method, then HTTP OPTIONS should be ok, and the CORS erros would go away.

Asp.Net web-api ajax call 404 method not found

I am using Asp.net mvc4 web-api.
I got an error 404 method not found, i am calling DelteMenu Method using jquery ajax. I am pssing argument Using data : of Jquery ajax. if i am passing Model parameter it is working fine but for other parameters like Guid, String throwing exception : 404 method nod found.please let me know if you have any idea why it is throwing 404 error.
//api method
public HttpResponseMessage DeleteMenu(Guid MenuId)
{
try
{
MenuDA.DeleteMenu(objMenuModel.MenuId);
return this.Request.CreateResponse(
HttpStatusCode.OK,
new
{
Success = true
});
}
catch (Exception ex)
{
ErrorLogDA.LogException(ex);
throw ex;
}
}
//Jquery ajax function
function performdeletemenu(MenuId)
{
if (confirm('Are you sure you want to delete this menu?'))
{
$.ajax({
type: 'DELETE',
url: '/api/MenuWebApi/DeleteMenu/',
data: "MenuId=" + MenuId,
success: function (data)
{
if (data.Success == true)
{
GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
Regards
The data setting does not work when sending a HTTP DELETE through jQuery's ajax function. You will have to pass the Guid in the url itself: url: '/api/MenuWebApi/DeleteMenu?MenuId=' + MenuId.
What I do find strange is that a 404 is returned, instead of a 400 Bad Request.
Add this line in RouteConfig.cs as below
routes.IgnoreRoute("{*x}", new { x = #".*\.asmx(/.*)?" });
I tool reference from https://stackoverflow.com/a/17058251/2318354
It will work definately in case of 404 Error Method not found.

AngularJS - $http post gets executed after second click

I'm trying to perform AngularJS post request via $http. My code looks like this:
$http({
url: "cgi-bin/post_event.pl",
method: "POST",
data : jsonToSend,
headers : {
'Content-Type' : "application/json",
}
}).success(function(data, status, headers, config) {
if (status === 200) {
console.log(data);
} else {
console.log(data);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
While looking via Firebug I see that this part of code gets executed, but none request is triggered towards server.
Only when I click it again, request hits server and success method is being called.
Anyone knows why's that? Or maybe I'm doing something wrong here...
This code with jQuery works fine:
$.ajax({
url: "cgi-bin/post_event.pl",
type: "POST",
contentType : "application/json",
data : JSON.stringify(jsonToSend),
success : function (data) {
console.log(data);
CurrentEvent.eventname = "";
CurrentEvent.starttime = "";
CurrentEvent.eventLocation.longitude = "";
CurrentEvent.eventLocation.latitude = "";
$window.location.href = "#/host/my_events";
},
error : function (data) {
// add error to $rootScope.errors
}
});
EDIT: Ah, sorry, I should be more detailed. This is called as callback after successful ajax request. Rest of the this code is just constructing jsonToSend.
So first time this part is being called I can see in firebug it constructs $http request but I can't see it triggered on server.
Next time I click on a button that does first time ajax request success method of this one is called (but id doesn't call it via callback from ajax, but it goes directly into success method)

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

Lost connection does not return error with jQuery AJAX on live site but on dev?

I am using the following code to post data from a asp.net 2.0 site to an asp.net 2.0 web service that post the data to a server:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {
// If not successfull
},
success: function (msg) {
deleteCustomer(customer.id);
}
});
I have a JavaScript function to check if I have connection or not, if I have I run the synchronisation (pulling data from web kit browser local database):
function checkConnection() {
var i = new Image();
i.onload = synchronise;
i.onerror = fail;
i.src = 'http://myurl.com/ping.gif?d=' + escape(Date());
setTimeout("checkConnection()", 60000); // Execute every minute
}
Thing is, if I run this locally and drop my internet connection the web service returns a 500 error (like I want it to do) and deleteCustomer(customer.id); is not called. However, on the live site if I drop my connection the web service does not return an error and deleteCustomer(customer.id); is called even if I don't have a connection to the internet (customer gets deleted from local database without being posted to the web server).
What's the reason for this? Please let me know if you need more code.
Thanks in advance.
You probably didn't wait a minute after dropping the connection.
There is a case that Ajax recall the cached data when you are ask for delete, and even if you are not connected to the net its get it from cache, so thats why its think that is all ok. The cache on jQuery Ajax is true by default.
So try with cache:false
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache:false,
error: function (xhr, status) {
// If not successfull
},
success: function (msg) {
deleteCustomer(customer.id);
}
});
For the image call, its better to use Interval and not create memory again and again.
<img id="PingerImg" width="1" height="1" src="/spacer.gif?" onload="synchronise" onerror="fail" />
<script language="javascript" type="text/javascript">
var myImg = document.getElementById("PingerImg");
if (myImg){
window.setInterval(function(){myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());}, 60000);
}
</script>
Update
The other solution is to really get a confirmation code form the server that you have delete the user, and only if you read that code , proceed to delete the user on remote.
success: function (msg) {
if(msg.confirm = true)
{
deleteCustomer(customer.id);
}
else
{
alert('Fail to delete user.');
}
}

Resources