0

我正在尝试从 MVC4 移动应用程序显示自定义错误页面,但只显示“错误加载页面”黄色消息而不是我的自定义页面。

我已尝试在操作和控制器上使用如下HandleErrorAttribute ,但没有成功

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]

我也尝试过覆盖我的基本控制器的 OnException 方法,但这似乎也没有任何效果。

 protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
                base.OnException(filterContext);

            Logger.LogException(filterContext.Exception);

            if (filterContext.Exception is SqlException)
                {
                filterContext.Result = new ViewResult { ViewName = "DatabaseError" };
                }

            if (filterContext.Exception is SomeOtherException)
                {
                filterContext.Result = new ViewResult { ViewName = "Error" };
                }

            if (filterContext.HttpContext.IsCustomErrorEnabled)
                {
                filterContext.ExceptionHandled = true;
                filterContext.Result.ExecuteResult(this.ControllerContext);
                }
        }

如果我在非 jQueryMobile MVC4 应用程序上尝试这些方法,它们会按预期工作,只是不在我的移动应用程序中!

任何人都对为什么以及如何使这项工作有任何见解?

4

2 回答 2

0

好的,通过禁用 Ajax,现在会显示相应的错误页面!

在我的 _layout.cshtml 页面中,我添加了以下 javascript:

 $.mobile.ajaxEnabled = false;
于 2012-11-19T19:32:05.050 回答
0

JsonResult如果请求是通过 AJAX 并返回 a而不是 a ,您可能需要检查您的过滤器ViewResult,例如:

public class TypeSwitchingHandleErrorAttribute : HandleErrorAttribute
{
    private static readonly string[] AJAX_ACCEPT_TYPES = new[] { "application/json", "application/javascript", "application/xml" };

    private bool IsAjax(ExceptionContext filterContext)
    {
        return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"
            ||
            filterContext.HttpContext.Request.AcceptTypes.ContainsAny(AJAX_ACCEPT_TYPES);
    }

    private void setResult(ExceptionContext filterContext, object content)
    {
        if( IsAjax(filterContext) )
        {
            filterContext.Result = new JsonResult { Data = content, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        } else
        {
            filterContext.Result = new ViewResult { ViewName = (string)content };
        }
    }

    public override void OnException(ExceptionContext filterContext)
    {
        // your code...then where you set the result...
        setResult(filterContext, "DatabaseError etc");
    }
}

然后,您必须在客户端适当地解释 ajax 响应。如果是 ajax 请求,您还可以发送不同的内容,例如标准{success: t/f, message: Exception.Message }对象,并适当地设置响应状态代码。

于 2014-12-04T21:37:15.937 回答