Można rozszerzyć atrybut [Authorize]
, aby można było zastąpić funkcję HandleUnauthorizedRequest
, aby zwrócić JsonResult
do połączenia 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);
}
}
utworzyć funkcję obsługi JavaScript przekierowanie:
<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>
a następnie wywołać tę funkcję w onSuccess opcji swojej Ajax.ActionLink
Ajax.ActionLink("Update Status", "GetStatus",
new AjaxOptions { OnSuccess="replaceStatus" })
Bardzo przyjemne rozwiązanie. Sugerowałbym zastąpienie instrukcji referrer.LocalPath.Replace ("/", "% 2f") systemem System.Web.HttpUtility.UrlEncode (referrer.PathAndQuery) w przypadku, gdy akcja AJAX przyjmuje również argumenty. – tranmq