Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect to new page after jquery ajax call in MVC if session timeout?

1- I have an Ajax link that call an action and that action returns a view , that view open in a specific Div (consider it as a menu that update the div with the corresponding view) 2- if session timeout the returned my logon view

so if i click on the link and session is timeout , the log on view open in the div not in the whole page

what i should do so if the session timeout it return logon view in new page in on my div?

like image 987
ToDayIsNow Avatar asked Feb 24 '11 09:02

ToDayIsNow


People also ask

Does jQuery ajax follow redirect?

jQuery's $. ajax appears to always follow redirects. How can I prevent this, and see the redirect without following it? There are various questions with titles like "jquery ajax redirect" but they all appear to involve accomplishing some other goal, rather than just directly checking the status that a server gives.

What is the default timeout for jQuery ajax?

The default value is 0 , which means there is no timeout.

Do ajax calls keep session alive?

Ajax calls will keep the session alive. One approach will be to set a timeout on client side to delete cookie after some time.


1 Answers

An efficient way to handle a session expiry is to create a custom Authorization attribute and return a HTTP 403 response if the session has expired and were dealing with an ajax request.

To create an Ajax aware authorization attribute you can inherit from AuthorizeAttribute and override the HandleUnauthorizedRequest event with a check on the type of request eg. IsAjaxRequest()

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // Fire back an unauthorized response
            filterContext.HttpContext.Response.StatusCode = 403;
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Then just decorate your controllers or actions with the AjaxAuthorize attribute just as you normally would with Authorize

[AjaxAuthorize(Roles = "1,2,3,4,5")]
public class HomeController 
{

Then if you're using jQuery you can handle the 403 response by creating a global ajax error handler.

    $.ajaxSetup({
        error: function (x, e) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location = "/login";
            }
        }
    });
like image 68
Chet Avatar answered Sep 22 '22 18:09

Chet