ASP.NET MVC forces an AJAX request be redirected to the login page when the FormsLogin session is no longer active

Viewed 9557

I have some AJAX calls that render PartialViewResults via the jQuery.AJAX method. This works great, I get my views rendered exactly the way I want.

The problem arises when I leave the page up for a while and the Forms auth session expires. When I click an action that performs an AJAX request, it shows the login page in my div.

I want it to redirect the WHOLE page to the login page.

3 Answers

When I have FormsAuthentication in place, I will include the Login URL in the answer https://stackoverflow.com/a/3431350/1559213 provided by @Chris Kooken

protected void Application_EndRequest()
    {

        var context = new HttpContextWrapper(Context);
        // If we're an ajax request, and doing a 302, then we actually need to do a 401
        if (Context.Response.StatusCode == 302 && context.Request.IsAjaxRequest() && 
            Context.Response.RedirectLocation.Contains(FormsAuthentication.LoginUrl))
        {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }
Related