@cem 的回答对我真的很有帮助,我添加了一个小改动,包括使用 antiforgerytoken 和过期会话的 ajax 调用场景。
public void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception as HttpAntiForgeryException;
if (exception == null) return;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.ExceptionHandled = true;
}
else
{
var routeValues = new RouteValueDictionary
{
["controller"] = "Account",
["action"] = "Login"
};
filterContext.Result = new RedirectToRouteResult(routeValues);
filterContext.ExceptionHandled = true;
}
}
...在客户端,您可以添加一个全局 ajax 错误处理程序以重定向到登录屏幕...
$.ajaxSetup({
error: function (x) {
if (x.status === 403) {
window.location = "/Account/Login";
}
}
});