Ali Ersöz Ali Ersöz - 1 month ago 25x
jQuery Question

How to reload page when an ajax request returns FormsAuthentication.RedirectToLoginPage?

I am a little in a trouble to find out how to redirect an ajax request to the login page when using forms authentication in mvc.

In OnAuthorize method I know that the request needs authorization. And if the cookie was deleted because of timeout etc., I want to redirect the user to the login page. But generally the requests are triggered by jquery via ajax request. So the requests are returning the html of the login page.

So how can I redirect the user to login page for an ajax request? Any ideas?


You could write a custom authorize attribute which would test if the request was an AJAX request and if yes return a JSON containing the url to redirect to:

public class MyAuthorizeAttribute : AuthorizeAttribute
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        if (filterContext.HttpContext.Request.IsAjaxRequest())
            // It was an AJAX request => no need to redirect
            // to the login url, just return a JSON object
            // pointing to this url so that the redirect is done 
            // on the client
            filterContext.Result = new JsonResult
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { redirectTo = FormsAuthentication.LoginUrl }
            // standard request => redirect

and then when you make an AJAX request:

$.get('/foo', function(result) {
    if (result.redirectTo) {
        window.location.href = result.redirectTo;
    } else {
        // standard stuff

and of course to avoid repeating this in every AJAX call you could use the .ajaxComplete() handler.