Global ajax error handling for asp.net WEBFORMS session timeout

Hi there,

I have an aspx website (webforms, not MVC!), which has the timeout set to 1 minute. After the timeout has elasped, asp.net calls Session_End method inside of my Global.asax page.

All is well, however, the site is heavily coded to use ajax calls into asp.net WebMethods, and after the timeout has elapsed, the response back from aspx is a 500, internal error.

How, can I handle the fact that the session has timeout, and redirect the users using ajax?

I have this so far, which just looks for the code 500, it doesnt work, and feels messy anyway. Plus, Id need to apply it to every ajax call:

 $.ajax({
        type: "POST",
        url: "Default.aspx/GetNetWorkMessage",
        cache: false,
        data: JSON.stringify({ messageId: messageId, status:statusCode, message: message }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(xhr) {
            var contentType = xhr.getResponseHeader("Content-Type");
            if (xhr.StatusCode=== 500) {
                   window.location.href = "/Account/Login.aspx";
            }
        },
        success: function (msg) {
            if (msg.d === "false") {
                window.location.href = "~/Account/Login.aspx";
            } else {
                $("#rawMessage").html(msg.d);
            }
            
        }
    });

Open in new window

LVL 1
Wayne AthertonProduct Analyst Financial Messaging LondonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CtrlAltDlCommented:
Do you want the ajax calls to keep the session alive?  If so, you could add EnableSession to your WebMethod.  That way anytime that web service is called the session timeout timer is reset.

[WebMethod(EnableSession = true)]
public string GetNetWorkMessage()
{
}

Open in new window

0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Would this then automatically divert the user to the aspx login page. Basically, I'm trying to prevent the end user clicking on a Ajax call and nothing happening because the aspx session has timed out
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
No one else got this issue then?
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

RobOwner (Aidellio)Commented:
Hi Wayne,

May look messy but unfortunately that's all you've got to work with within a browser.

Can you confirm which of your error or success functions is called with a 500 error?

E.g.

success: function(d) {
    console.dir(d);
},
error: function(jqXHR, status, errorString) {
    console.dir(status);
    console.dir(errorString);
}
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Hi Rob,

this is an example method being used:

 error: function(xhr) {
            // var contentType = xhr.getResponseHeader("Content-Type");
            if (xhr.status === 500) {
                window.location.href = "/Account/Login.aspx";
            }
        },
        success: function(msg) {

            if (msg.d) {
                $("span#dowJonesListDate").text(msg.d);
            }
        }

Open in new window


I'm trying to figure out a way of gracefully, redirecting the user to the login page, when the ASP.NET session expires. But this is proving to be a very difficult task to achieve.
0
RobOwner (Aidellio)Commented:
Do you actually get a 500 error on your page when a user isn't logged in?  That to me doesn't make sense as it is essentially saying that your server throws an error (that isn't caught) when a user tries to access a page and isn't logged in.

Typically your ajax request should return 200 for a successful connection regardless of the state of the login of the user.  In otherwords, the success() function should always be called because the connection and transfer of data back and forth was correct.

AJAX requests should either return html or json formatted data.  I prefer json as it allows me to add other data around the content.  For instance, in this situation, I would return a json object that contains all the required data as well as a variable "loggedin".  If it is true then you continue on the page, if it is false then you redirect.

What data format are you returning from your webservice?
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
So, to give a bit of background.... I did have the above 200 requests, but this wasn't capturing the fact that an ASP.NET session had expired. So, a user could still send a post to the server, and expect something to happen, but behind the scenes, ASP.NET (irrespective of the actually code, and in this instance it was a 401), would return a 500 error code.

I know, this is bad, but it's the only way, for the time being, I can force the user to log back in, in order to restore the session variables.
0
RobOwner (Aidellio)Commented:
Hey we all do stuff that isn't picture book perfect. I understand where you're coming from.
So that I understand, if the user is logged in there'll be a response code of 200. If they're not logged in (session timeout) then your script sends a response of 500?
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Yeah, but this isn't ideal, as it could genuinely be a 500, for which I'd need to manage more gracefully, then just sending the user to the log in page. :-)
0
RobOwner (Aidellio)Commented:
ok so you need to change the flow of what's going on here.

what do you have control of and what do you not?

Ideally it should always be a response of 200 unless there is a real 500 error.  Can you make that happen?  Then we look at filtering the POSTs when the user is logged out.
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Hi Rob,

Sorry for the late response, been on my holidays.

I can make a real 500, but it's getting that back to the client.
0
RobOwner (Aidellio)Commented:
Just going back a step to http:#a40821115.  Can you confirm that when you send a 500 does it go into the error handler or the success handler?
0
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Hi Rob,

it drops into the error handler.
0
RobOwner (Aidellio)Commented:
So my next question is why is your server returning a code 500 when the user isn't logged in?
It's appears to crash your server by posting data to it when you're not logged in? That could have other ramifications
1
Wayne AthertonProduct Analyst Financial Messaging LondonAuthor Commented:
Hi Rob,

I dont disagree, but I was looking for a quick win, to prevent the system falling over. As, you appear to be the only one responding to this request, can I ask, how you would handle such a situation.

So, user logs in. ASP.NET session expires, but JQuery/Ajax calls are still made. How should my Ajax code handle this.
0
RobOwner (Aidellio)Commented:
The issue here is your server returning the 500 when the user isn't logged in.  If it were me, i'd be returning something to the effect of "you're not logged in".  Takes the html response code out of the equation.  It should ALWAYS be a 200 (unless you do a redirect etc).  Save the ajax error handler for communication errors such as 404 (page not found) and 500 (server error).

Typically now with all my Ajax requests, I'm returning JSON.  I include a flag in that data to say if there's an error or not.

If your ajax request returns an error then you take the appropriate action, like redirect (which you mentioned before).

e.g. (You could do this with XML if you felt more comfortable using that.)

// when there's an error
{
    "error": true,
    "message": "Session has timed out"
}

//or if everything is ok
{
    "error": false,
    "message": "",
    "data": "your data goes here"
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.