Ajax.ActionLink returns the login page to the div when the user needs to login again

I have Ajax.ActionLinkone that results in a partial view return. However, if mine FormsAuthenticationexpires and the user needs to log in again, the entire login page will be returned as a partial view.

This will result in a full login page appearing in div, which I have selected for partial viewing. Thus, it looks like two web pages per page.

I use the attribute [Authorize]on my controller and actions.

How can I force the login page back as a full view?

+5
source share
1 answer

You can expand the attribute [Authorize]so that you can override the function HandleUnauthorizedRequestto return JsonResultto your AJAX call.

public class AuthorizeAjaxAttribute : 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

            var referrer = filterContext.HttpContext.Request.UrlReferrer;

            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { redirectTo = FormsAuthentication.LoginUrl + 
                            "?ReturnUrl=" + 
                             referrer.LocalPath.Replace("/", "%2f") }
            };
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Create a Javascript function handling redirection:

<script type="text/javascript">
    function replaceStatus(result) {
        // if redirectTo has a value, redirect to the link
        if (result.redirectTo) {
            window.location.href = result.redirectTo;
        }
        else {
            // when the AJAX succeeds refresh the mydiv section
            $('#mydiv').html(result);
        }
    };
</script>

And then call this function in the OnSuccess option of your Ajax.ActionLink

Ajax.ActionLink("Update Status", "GetStatus", 
                 new AjaxOptions { OnSuccess="replaceStatus" })
+5
source

All Articles