Asp.net mvc ASP.NET MVC 3中随Ajax响应发送的自定义错误页

Asp.net mvc ASP.NET MVC 3中随Ajax响应发送的自定义错误页,asp.net-mvc,error-handling,Asp.net Mvc,Error Handling,当发生错误时,为什么自定义错误页面会与下面的ajax响应一起发送 回应 {"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Error</titl

当发生错误时,为什么自定义错误页面会与下面的ajax响应一起发送

回应

{"Errors":["An error has occurred and we have been notified.  We are sorry for the inconvenience."]}<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Error</title>

我添加了response.End();它成功了。有更好的方法吗?

如果有人仍然存在此问题,我找到了一个稍微干净一点的解决方案:

if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
        //non-ajax exception handling code here
}
else
{
        filterContext.Result = new HttpStatusCodeResult(500);
        filterContext.ExceptionHandled = true;
}

dsomuah的解决方案很好,但必须添加到每个服务Ajax请求的控制器中。我们进一步在全球范围内注册了以下操作过滤器:

public class HandleAjaxErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
    }
}

虽然dsomuah的代码可以很容易地进入您的控制器基类,因为许多项目由于各种原因已经实现了,但是很高兴看到这里列出了这个方法+1.
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
        //non-ajax exception handling code here
}
else
{
        filterContext.Result = new HttpStatusCodeResult(500);
        filterContext.ExceptionHandled = true;
}
public class HandleAjaxErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
        }
    }
}