2012-11-18 60 views
0

我试图从MVC4移动应用程序显示一个自定义错误页面,但不断显示“Error Loading Page”黄色消息而不是我的自定义页面。MVC4 jQueryMobile不会显示自定义错误页面OnException

我一直在使用下面上的操作,控制器没有成功

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

我也试图重写我的基本控制器的onException的方法HandleErrorAttribute尝试,但这个还没有出现有任何影响。

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应用这些方法,只是没有在我的移动应用程序!

任何人都知道为什么以及如何使这项工作?

回答

0

好吧,通过禁用Ajax,现在显示适当的错误页面!

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

$.mobile.ajaxEnabled = false; 
0

你可能需要在你的过滤器,以检查是否请求是通过AJAX和返回JsonResult代替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 }对象,并且也适当地设置响应状态码。

相关问题