您可以擴展[Authorize]
屬性,以便覆蓋HandleUnauthorizedRequest
函數以將JsonResult
返回給您的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);
}
}
創建一個JavaScript函數處理重定向:
<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>
然後調用這個函數在Ajax.ActionLink
Ajax.ActionLink("Update Status", "GetStatus",
new AjaxOptions { OnSuccess="replaceStatus" })
很不錯的解決方案的的onSuccess選項。如果AJAX操作也需要參數,我會建議用System.Web.HttpUtility.UrlEncode(referrer.PathAndQuery)替換語句referrer.LocalPath.Replace(「/」,「%2f」)。 – tranmq