How can I check if my MVC session has ended using ajax?

I have my web.config set and it works fine, but only when the user does an httpPost does it recognize that it should redirect:

  <system.web>
<sessionState mode="InProc" timeout="5" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<authentication mode="Forms">
  <forms loginUrl="~/Login/Login"></forms>
</authentication>

      

I have this code set in my _Layout:

var _redirectUrl = '@Url.Action("Logout", "Login")';
$(document).ajaxSuccess(function (event, request, settings, xhr, props, jqXHR) {
            if (jqXHR.status == 401) {
                window.location.href = _redirectUrl;
            }
        });

      

jqXHR.status returns undefined in my browser debuger, I also tried props.status and still get undefined. Any suggestions?

+3


source to share


1 answer


A request for a timed out session will result in an http status 302 (Found), which will result in transparent redirects. Therefore jQuery doesn't handle this automatically. You could return the server http status 401 (unauthorized) instead of redirecting. Here is an article with code you can copy to do this:



http://blogs.perficient.com/microsoft/2014/02/gracefully-handle-mvc-user-session-expiration-in-javascript/

+2


source







All Articles