Return a 401 to the JavaScript when the session has expired
I have an ASP.NET MVC 3 application which uses forms authentication.
Forms authentication has been setup as follows in the web.config.
<authentication mode="Forms">
<forms loginUrl="Session/LogIn"
protection="All"
timeout="60"
slidingExpiration="true"
/>
</authentication>
When the session expires and I click on something which results in a regular HTTP call, the Session/Login page is shown. Which is all good.
But, when the session expires and I click on something which results in an AJAX ca开发者_JAVA百科ll, the Session/Login page is embedded inside the HTML element which the AJAX call was going to update. i.e. if the AJAX call was to update a div with an id of 123, and because the session expired, then the login form will be placed inside that div.
What I would like to do is to check in the ASP.NET MVC 3 application when the session has expired. If it has, and the call is an AJAX one, then I would like to return no content as the response, and set the return status code to a 401.
In the JavaScript (using jQuery), I can then look for the unauthorised status code of 401, and redirect the user to the Login page. Something like this:
$(document).ajaxError(function(event, response, settings, error) {
if (response.status == 401) {
window.document.location = "Login";
}
});
So what I am looking for is a sure way to check that the session has expired on the C# side, and return an empty response with a status code of 401 which then the JavaScript can handle with cleanly.
in the action that returns the login page (Sesssion/LogIn)
check if this is an ajax request,
if(Request.IsAjaxRequest)
and if it is return a Content("<meta http-equiv='refresh' content='0'>");
instead of View()
精彩评论