È possibile estendere l'attributo [Authorize]
in modo da poter sostituire la funzione HandleUnauthorizedRequest
per restituire un numero JsonResult
alla chiamata AJAX.
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);
}
}
creare una funzione Javascript gestire il reindirizzamento:
<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>
e quindi chiamare tale funzione nell'opzione OnSuccess del vostro Ajax.ActionLink
Ajax.ActionLink("Update Status", "GetStatus",
new AjaxOptions { OnSuccess="replaceStatus" })
Molto bella soluzione. Suggerirei di sostituire l'istruzione referrer.LocalPath.Replace ("/", "% 2f") con System.Web.HttpUtility.UrlEncode (referrer.PathAndQuery) nel caso in cui l'azione AJAX accetta anche argomenti. – tranmq