ASP.NET MVC redirect to login page with AJAX

If you use the [Authorize] attribute on your MVC controller then your users will automatically be redirected to the login page when they GET or POST if their session or cookie has expired. However if you are using the AJAX helpers to redirect output into a panel on the page this just results in the login page appearing in the panel, rather than the whole page. And quite often you will find that it does not work anyway as it seems to lose any information that it might have had about what virtual directories it is in.

A solution for this is quite simple, but I’ve not as yet found anywhere else on the web that puts it all together. So instead of [Authorise] apply the following to your controller constructor (or action):

public class MyController : Controller

The source for the CustomAuthorise attribute is as below (obviously substitute in your own login URL!). Note that you can still use other custom authorise attributes if you do this, e.g. a role checker.

 public class CustomAuthoriseAttribute: AuthorizeAttribute
        public override void OnAuthorization(AuthorizationContext filterContext)
            if (filterContext.Result == null || (filterContext.Result.GetType() != typeof(HttpUnauthorizedResult)
                || !filterContext.HttpContext.Request.IsAjaxRequest()))

            var redirectToUrl = "Security/LogOn?returnUrl=" + filterContext.HttpContext.Request.UrlReferrer.PathAndQuery;

            filterContext.Result =  new JavaScriptResult() { Script="window.location = '" + redirectToUrl + "'"};

Thanks to these posts elsewhere on the web for helping out: