Ajax.BeginForm OnFailure return empty result when connecting via HTTPS - model-view-controller

When connecting via a non-secured protocol (http), my MVC 5 web application returns the error message properly. But the moment I connect via https, the error message is blank. Thought? NOTE: I try json return also. Thanks!
Browser debugger output
HTTP
HTTPS
MVC Controller:
string message = string.Join(" ", errors);
Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
return new HttpStatusCodeResult(Response.StatusCode, string.Join(" ", message));
Script:
function ajaxOnFailure(response, status, error) {
debugger;
if (response.status == 500) {
error = "An internal error has occurred. Please try again. If the problem persists, please contact IT."
}
toastr.error("", error);
}

I ended up using a workaround. Instead of return a fail response, I return OK response and determine the type of message via jquery. It would have been nice if a fail response return the message via https.

Related

No headers available in xhr object when an UNAUTHORIZED error occurs - IE10

I have a CORS Ajax call to a web api. I have a message handler which throws an:
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
throw new HttpResponseException(msg);
On the client I can't get no response headers, tried:
error: function (xhr, error) {
var result = xhr.getResponseHeader("Response");
but result is null and no other heades are available.
The Debugger shows correctly a 401!
Should I return the Unauthorized Exception differently from the server?
Update:
I forgot the add the Origin header to my HttpResponseException, in order to get the headers.
But in IE10 I don't get any headers, only error message
"error"
How can I know what happend, when using IE10?
Here is related question.
As I cannot get the Headers when returning a 401 response.
No instead I return NoContent StatusCode, which triggers the AJAX success eventhandler.
Now I have to check the response header "response" (which I manually add on the server side) in the success eventhandler, in order to make it work in IE 10:
Server:
var msg = new HttpResponseMessage(HttpStatusCode.NoContent) { ReasonPhrase = "UNAUTHORIZED" };
msg.Headers.Add("RESPONSE", "401");
AddCORSHeaders(msg.Headers, request);
return await Task.FromResult(msg);
Client:
error: function (jqXhr, error) {
var isAuth= jqXhr.getResponseHeader("Response");
Now I get a "response" header with value 401.
IF SOMEONE HAS A BETTER APPROACH, I'LL EXCEPT THE ANSWER !
In IE10 the ajax error eventhandler you get readyState=0 and status="".
In Chrome you get a 401 and readyState=4.

Cannot access error response body from client when using nginx + lua

I'm using the following lua script to forward all server responses that are served from Node. My error handling for a /signup route works as follows:
if authenticationResult.status ~= 201 then
...
ngx.status = authenticationResult.status
ngx.say(authenticationResult.body)
ngx.exit(401)
return
end
From the client I send a typical signup request like so, using the superagent-promise library:
request
.post(url)
.type('form')
.send(data)
.end()
.then((response) => {
console.log('the response', response)
})
.catch((error) => {
console.log('the error', error)
})
When I send a valid post request from the client, the response variable in the .then successfully contains the response body.
However, when I sent an improper post request with invalid credentials, neither the .then nor the .catch executes. Instead, the Chrome console immediately displays POST http://api.dockerhost/signup 401 (Unauthorized).
I would like to know what I can do differently to successfully access the server's error response and its contents, outside of just its status code.
Per the manual, you need to use ngx.HTTP_OK as the return if you want nginx to return content as part of the page. Otherwise it will simply return a 401.
ngx.status = authenticationResult.status
ngx.say(authenticationResult.body)
ngx.exit(ngx.HTTP_OK)
return

IdHTTP: EIdException ResponseCode (Colorize + Replace)

I have two problems here. So I need your help.
The result of microsoft.com's response code is some time HTTP/1.1 403 Forbidden or HTTP/1.1 200 OK.`
try
{
IdHTTP->Get("http://www.microsoft.com");
ListBox->Items->Add(IdHTTP->Response->ResponseCode);
}
catch (const EIdException &E)
{
ListBox->Items->Add(E.Message);
ListBox->Items->Add(IdHTTP->Response->ResponseText);
}
But when I checked it on http://web-sniffer.net/ or http://tools.seobook.com/server-header-checker then its results is HTTP/1.1 302 Moved Temporarily.
Why the results from IdHTTP is different from the both url above?. How can IdHTTP achieve the same http status code?.
Colorize & replace E.Message error of EIdException / Exception in TListBox.
For example, I want to replace the "Socket Error # 10061Connection refused" with "your connection is refused".
ListBox->Items->Add(StringReplace(E.Message,"Socket Error # 10061Connection refused.","your connection is refused.",TReplaceFlags()<<rfReplaceAll));
But using that way, the result is still same.
Thanks for taking the time to read this. Any help or suggestions with would be greatly appreciated!!
Outside of site maintenance, I doubt http://www.microsoft.com would ever return a 403 Forbidden error under normal conditions. But, like any site, I suppose it could happen at times. It is a fatal error, you cannot access the URL at that time (if at all).
302 Moved Temporarily is an HTTP redirect. The TIdHTTP.OnRedirect event will be triggered to give you the new URL. If the TIdHTTP.HandleRedirects property is true, or the OnRedirect event handler returns true, TIdHTTP will handle the redirect internally and automatically request the new URL for you. TIdHTTP.Get() does not exit until the final URL is reached, or an error occurs.
As for error handling, if you want to customize the message you display based on the type of error that occurred, you need to actually differentiate between the various types of errors that can occur, eg:
try
{
IdHTTP->Get("http://www.microsoft.com");
ListBox->Items->Add(IdHTTP->Response->ResponseCode);
}
catch (const EIdHTTPProtocolException &E)
{
// HTTP error
// E.ErrorCode contains the ResponseCode
// E.Message contains the ResponseText
// E.ErrorMessage contains the content of the error body, if any
ListBox->Items->Add(E.Message);
}
catch (const EIdSocketError &E)
{
// Socket error
// E.LastError contains the socket error code
// E.Message contains the socket error message
if (E.LastError == Id_WSAECONNREFUSED)
ListBox->Items->Add("Your connection is refused");
else
ListBox->Items->Add(E.Message);
}
catch (const EIdException &E)
{
// any other Indy error
ListBox->Items->Add(E.Message);
}
catch (const Exception &E)
{
// any other non-Indy error
ListBox->Items->Add(E.Message);
}

Status of ajax or post request

status - contains the status of the request like
("success", "notmodified", "error", "timeout", or "parsererror") /ajax or post
I know what is success,not modified,error meant here but I am unable to find out how to handle this errors. If the call back is success then update my div, if there is any error not modified, error, time out, parse error then let me alert a pop up some error occurred.
What would be the cause for each type of error? I mean the situations where not modified,timeout,error and parseerror occurs.
If it results success, then does it mean my post request has successfully worked?
My local-server xampp never results any error, the status is always success. I guess, since its limited to my system but when I put my website online there exists several issues like traffic on server.
So how do I find out, whether my post request to some sample.php page was successfully sent and else pop out an alert to user if something went wrong?
The error types are a little self-explanatory. They simply provide a string for you to easily handle the different errors.
error callback option is invoked, if the request fails. It receives the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
Source: jQuery.Ajax documentation
Codes Explained:
Error: Any of the HTTP response codes, like the well-know 404 (not found) or other internal server errors.
Notmodified: Compares the cached version of the browser with the server's version. If they are the same, the server responds with a 304
Timeout: Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.
Parse Error: The jQuery data (JSON) cannot be parsed (usually due to syntax errors)
Handling these error codes:
Here is some example of handling the errors
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
Source: Blog Post - jQuery Error Handling
Success
Response code is between 200-299 or is 304 Not Modified.
Not Modified
Response code is 304. If you employ caching, the browser can tell the server which version it currently has, and the server compares this with its version and if there has been no change, it can send a 304 Not Modified response, to indicate to the client that their version is up to date. In jQuery ajax, a 304 Not Modified response will still fire the success handler.
Error
Response code is between 400-599. This could be for example 404 not found, 403 forbidden, 500 internal server error etc.
Parse Error
This is a jQuery internal, not actually a HTTP response. This will happen if jQuery is trying to parse JSON or XML that is not in the valid format or has syntax errors.
Timeout
Again, this isn't a HTTP response. The ajax request has a timeout which if is exceeded before the server responds, will abort the request.
If you control the server side, in your example a PHP script, and you never change the response code using header() then your ajax will always receive 200 OK responses unless there is an unhandled exception in the PHP which will trigger a 500 internal server error.
It is acceptable to always send 200 OK response codes. For example, if the server outputs a JSON object which contains its own success/error flag then any errors can be handled by looking at the flag.
As far as I know
not modified: Server sends a Not Modified(304) response status
timeout: the server has not responded within the time period specified by the timeout property
error: server response with a error status like 4xx or 5xx
parseerror: there was an client side error when processing server response like an invalid json format/xml format

AJAX 504 when calling ASP.NET Web API

My AJAX call is returning a 504 error when calling an ASP.NET Web API action.
More info:
Here's my API action:
public HttpResponseMessage Get(string fileName, int feedID)
{
try
{
// create file...
return new HttpResponseMessage { Content = new StringContent("Complete."), StatusCode = HttpStatusCode.OK };
}
catch (Exception ex)
{
Log.WriteError(ex);
throw new HttpResponseException(new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
Content = new StringContent("An error has occurred.")
});
}
}
Here's my AJAX call:
$.ajax({
url: url,
type: 'GET',
success: function () {
$("#lblProgressDownload").hide();
window.open("Previews/" + fileName);
},
error: function (xhr, status, error) {
$("#lblProgressDownload").hide();
alert("Error downloading feed preview: " + error);
}
});
I get a 504 error (viewed in fiddler/ chrome console) when the file takes too long to create. The "error" parameter in the error callback doesn't return anything.
I only get the 504 error when it's hosted - on my dev it works fine.
How do I prevent this 504 error?
Note, I already tried changing the executionTimeout property in my web.config, as well as the ajax timeout. Neither worked.
HTTP error 504 is a gateway timeout:
The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI [...] in attempting to complete the request.
I suspect that means there is a proxy or gateway somewhere between you and the production server, but not your dev server, which is why it fails on the one but not the other.
Your choice is either to make your server code fast enough that it doesn't trigger the timeout, or get whoever is running the proxy server to relax their timeout restrictions (assuming it's something that you or your company controls).

Resources