ASP.NET MVC Ajax错误返回视图而不是ajax

ASP.NET MVC Ajax Error returning view instead of ajax

我正在通过Ajax对一个方法进行一个ASP.NET MVC调用,这个错误引发了一个异常。我希望将异常的消息传递回客户机,而不必捕获异常。像这样:

1
2
3
4
5
6
7
[HttpPost]
public ActionResult AddUser(User user) {
  if (UserIsValid(user)) {
    return Json(new { resultText ="Success!" });
  }
  throw new Exception("The user was invalid.  Please fill out the entire form.");
}

我在Firebug响应中看到一个HTML页面

1
2
3
4
5
<!DOCTYPE html>
<html>
    <head>
       "The user was invalid.  Please fill out the entire form."
        .....

我不想被强迫用一个try-catch块来做这个。是否有方法自动获取jquery$(document).ajaxerror(函数()读取此异常消息?这是不好的做法吗?我可以覆盖控制器一个例外吗?或者我必须尝试/捕获并返回JSON?

像这样的东西很不错:

1
2
3
$(document).ajaxError(function (data) {
    alert(data.title);        
});


您可以使用自定义筛选器执行此操作:

1
2
3
$(document).ajaxError(function(event, jqxhr) {
    console.log(jqxhr.responseText);
});

-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[HttpPost]
[CustomHandleErrorAttribute]
public JsonResult Foo(bool isTrue)
{
    if (isTrue)
    {
        return Json(new { Foo ="Bar" });
    }
    throw new HttpException(404,"Oh noes...");
}

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var exception = filterContext.Exception;
        var statusCode = new HttpException(null, exception).GetHttpCode();

        filterContext.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet, //Not necessary for this example
            Data = new
            {
                error = true,
                message = filterContext.Exception.Message
            }
        };

        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = statusCode;  
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
}

有点受这个blogpost的启发:http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc


与其处理服务器引发的异常,为什么JSON响应中没有标志呢?

1
2
3
4
5
6
7
8
[HttpPost]
public ActionResult AddUser(User user) {
  if (UserIsValid(user)) {
    return Json(new { success = true, resultText ="Success!" });
  }

  return Json(new { success = false, resultText ="The user was invalid.  Please fill out the entire form." });
}