我有一个 Ajax 在 Controller 中调用 HTTP Post Action 方法。
此操作方法抛出一个简单的异常消息。
我用自己的自定义处理程序属性装饰了 Controller ,如下所示:
public override void OnException(ExceptionContext filterContext) {
if (!filterContext.ExceptionHandled) {
string actionName = filterContext.RouteData.Values["action"].ToString();
Type controllerType = filterContext.Controller.GetType();
var method = controllerType.GetMethod(actionName);
var returnType = method.ReturnType;
string controllerName = filterContext.RouteData.Values["controller"].ToString();
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
// redirect on error
filterContext.Result = new ViewResult {
ViewName = "Error",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
};
}
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
上述问题是,由于某种原因,使用 POST 方法时,我的页面不会重定向到错误 View 。但是,如果我调用已用 [HttpGet] 修饰的操作方法,我的重定向将正常工作。
是否可以将 AJAX 方法重定向到错误 View ,因为我希望错误 View 页面处理所有错误?
最佳答案
您可以像这样附加全局 ajax 错误处理程序:
$(function() {
$(document).ajaxError(function(xhr, props) {
if (props.status >= 200 && props.status < 300 || props.status === 304) {
//all is well
} else {
alert("error");
window.location = "/Error/CustomError";
}
});
});
关于c# - AJAX 调用后如何重定向到 "Error" View 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36004063/