我正在尝试从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应用程序上尝试这些方法,它们按预期工作,而不是在我的移动应用程序中!
任何人都知道为什么以及如何使这项工作?
答案 0 :(得分: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 }
对象),您也可以发送不同的内容,并且还可以适当地设置响应状态代码。