session timeout on ajax call

Ashwini Verma picture Ashwini Verma · Dec 31, 2012 · Viewed 15.5k times · Source

I know this is duplicate but I could not get reliable solution(for asp.net web).

I just want to redirect to the login page if session expires. I have tried following:

1. using jquery status code

    $.ajax({
     type: "POST",
     url: "stream.asmx/SomeMethod",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (msg) {
        //success msg
     },
     error: function (request, status, error) {
        if (status = 403) {
            location.href = 'login.aspx';
        }
     }
    });

Problem: this returns same status code(403) for other errors too, which I only expect for session timeout.

2. Sending json message whether session expired

code behind:

    if (!object.Equals(HttpContext.Current.Session["User"], null))
    {
        Id = int.Parse(HttpContext.Current.Session["User"].ToString());
    }
    else
    {
        result = from row in dtscrab.AsEnumerable()
                 select new
                 {
                     redirectUrl = "login.aspx",
                     isRedirect = true
                 };
    }

on $.ajax success:

    success: function (msg) {
        if (msg.d[0].isRedirect) {
            window.location.href = msg.d[0].redirectUrl;
        }
        else {
            //load containt
        }
     }

Problem: It's somehow desn't invoke ajax success line if session expires(it does return correct json). And even this is not a proper way if I have many number of ajax request in the page(should be handled globally).

However, I saw this post which is really good soltion but it's for mvc using AuthorizeAttribute: handling-session-timeout-in-ajax-calls

So, Is there I can use same concept used in mvc using AuthorizeAttribute in asp.net web api? If not, how I can troubleshoot those issue which I'm facing (any of above two mentioned)?

Answer

Alex Schultz picture Alex Schultz · Jan 4, 2013

A 403 status code is going to cause jQuery to call the failure method. Keep the same code behind from your second try, but move the redirect handler to the failure method instead of the success method. In the success method, treat it as you normally would.