更新时间:2023-02-17 10:04:55
您可以使用自定义错误处理程序过滤器:
You could use a custom error handler filter:
public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { errorMessage = "some error message" }
};
}
}
}
然后装饰通过Ajax调用的控制器/动作,甚至注册为全局过滤器.
And then decorate your controller/actions that you are calling through Ajax or even register as global filter.
然后,在执行Ajax请求时,您可以测试error属性的存在:
Then when performing the Ajax request you can test the presence of the error property:
$.getJSON('/foo', function(result) {
if (result.errorMessage) {
// Something went wrong on the server
} else {
// Process as normally
}
});