jqueryasp.net-mvcasp.net-mvc-2session-cookiesexpired-sessions

Response content type different from what expected


I have a jquery calendar widget that do query several event sources on the server and these sources all returns the same JSON format responses.

What is really annoying is that when the user cookie expires these sources all redirect the user to the login page returning HTML content.

I have looked at the request with fiddler and I can see two request done: first one is a request from the jquery calendar object to update the events with http status 302 and immediately after a request to the login page with http status 200.

GET /xyz/Adempimenti/GetEvents?_=1289170335910&start=1288566000&end=1291590000 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/javascript, */*; q=0.01

HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /xyz/Login/LogOn?ReturnUrl=%2fxyz%2fAdempimenti%2fGetEvents%3f_%3d1289170335910%26start%3d1288566000%26end%3d1291590000&_=1289170335910&start=1288566000&end=1291590000

My site is deeply based on ajax calls and this one of the calendar is just an example to explain the problem i am facing to. I would like to avoid to handle the error on every ajax call and do a redirect. The optimal way would be to find a way to automatically disconnect the user when his session cookie expires. I have seen this implemented in some web email system that automatically create a dialog saying that the session has expired.

Any help on this direction?


Solution

  • When jQuery does an AJAX request, it sends the HTTP_X_REQUESTED_WITH header.

    Have you considered checking for that header on server side? If the session has timed out, instead of redirecting to the login page, you could return a JSON structure containing the "please log in" error message.

    That would be the cleanest method in my eyes.

    Another idea would be to make an additional Ajax request before doing the "real" one. If the first request fails or gets a text/html content type back, you know you are no longer logged in. Not very elegant but easier than trying to count the session duration on client side (which is bound to be unreliable).