Where is the best place to catch unauthorized 401 when activating a route that was previously authorized. This happens when for instance the authorization token is no longer valid, if the user tries to activate the route, there will be 401 error. The exception in Durandal is thrown at the activateItem Level, No idea though how to define a global handler for it.
Note. mapUnknownRoutes is of no use in this scenario
You catch the call from wherever you are making a call to your API from. If you are making the call with jQuery would you handle the AJAX call's failure with the fail method -
$.ajax({
url: url,
data: { start: start, end: end },
success: function(data, textStatus, jqXHR) {
$('#myElement').append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === '401') {
// do something
}
}
});
This gives you the status code, I can't remember if it is in string or int format though so that's pseudo code obviously
Related
I have this piece of code
function getMesssages(id,c) {
function waitForServerCall(id,c) {
$.get(href("~/polling/" + id), function (response) {
var r = c(response);
if (r) {
return false;
}
waitForServerCall(id);
});
}
waitForServerCall(id,c);
$.post(href("~/batch/export/?batches=3344&pollid=" + id), function (response) {
c(response);
cancelCall = true;
});
}
The $.get inside the waitForServerCall method only get execute when the $.post recive the server response. Why?
This is the ajaxSettings:
accepts: Object
async: true
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
contents: Object
converters: Object
flatOptions: Object
global: true
isLocal: false
jsonp: "callback"
jsonpCallback: ()
processData: true
responseFields: Object
type: "GET"
url: "http://localhost:59161/"
xhr: In()
__proto__: Object
Update.
What i am doing is long polling, the post request is a long running process so i need to know some events that the server will trigger, the waitForServerCall method notify the client about the events that occured. But since the $.get method execute once the $.post response is recive, the notification process don't work.
Update 1:
Im using .NET 4.0 and Jquery 1.9.1.
Yes, the $.get request gets execute first but not response is recive until the $.post get the response. Once the $.post get the response, $.get execute correctly. But I'm expecting the $.get to get the server response even if the $.post has not get any response yet.
So here is the answer of why.
All the credits goes to the author of this article:
http://josefottosson.se/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Stack trace is a list of the method calls that the application was in the middle of when an Exception was thrown.
How can i obtain stack trace if i use ajax(jquery) to access to it.
function loadCompFilterTreeInfo() {
var d = "";
$.ajax({
type: "GET",
async: false,
url: '<%=HandlerUrl%>',
dataType: "json",
data: {},
success: function (data) {
d = data;
},
error: function (e) {
alert('<%= Resources.Resource.ErrorRequestingDataFromServer%>');
}
});
return d;
};
In my case occurs alert.
So you have two layers that are interacting with each other
Client
Server
Your Javascript code runs on the client-side, but it's making an AJAX call to a resource that is on the server-side of things.
In this situation, if you are getting an error, it's because the server has encountered an error with processing the request. If the server throws the error, you should be able to catch the error and display it in your 'error' event:
error: function(jqXHR jqXHR, String textStatus, String errorThrown) {
alert('Error Thrown: ' + errorThrown);
}
Also, assuming you have some sort of error logging on the server, you can check your server-side error log for any errors that may have occurred.
I'm experimenting with SignalR hosted in an asp.net MVC5 application and am having an issue detecting authorization failures from a web client.
I have a simple hub as follows:
public class ChitChat : Hub
{
[Authorize]
public string Hi(string incoming)
{
Clients.All.echo(incoming);
return "Echoed " + incoming;
}
}
And on the web page:
$(function() {
var hub = $.connection.chitChat;
hub.client.echo = function(msg) {
console.log(msg);
}
$.connection.hub.start().done(function() {
console.log("Done starting hub");
hub.server.hi("Client message")
.done(function() {
console.log(arguments);
})
.fail(function() {
console.log(arguments);
});
})
.fail(function() {
console.log("Fail hub" + arguments);
});
});
When I enable detailed errors in the hub configuration, I get this in the promise rejection for hi
Error: Caller is not authorized to invoke the Hi method on ChitChat.
Without detailed errors, I just get
Error: There was an error invoking Hub method 'chitchat.Hi'.
I'd like to keep detailed errors off, but still get some dependable way of identifying auth failures (I'd assumed I would get a 401/403 code somewhere). Is there a way to achieve this?
SignalR uses jQuery under the hood, so detecting the 401 status code could be achieved by following:
$.ajaxSetup({
statusCode: {
401: function() {
// your code is here
}
}
});
Given a rejection r, check r.source.status. This should give you a 401/403 when it is an authorization problem.
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.
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.