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):

[CustomAuthorise]
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)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.Result == null || (filterContext.Result.GetType() != typeof(HttpUnauthorizedResult)
                || !filterContext.HttpContext.Request.IsAjaxRequest()))
                return;

            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:
http://craftycodeblog.com/2010/05/15/asp-net-mvc-ajax-redirect/
http://beckelman.net/2010/04/01/custom-aspnet-mvc-authorization-attribute-for-ajax-requests/

Advertisements