您的位置:首页 > 其它

MVC.Net:通过Global.asax捕捉错误

2014-06-22 21:00 274 查看
在MVC.Net中,如果我们想做一个统一的错误处理的模块,有几个选择,一种是通过一个Base Controller来实现,另外一种就是在Global.asax中实现。这里介绍后一种方法。

首先打开Global.asax文件,然后添加如下代码:

/**
* 捕捉系统级错误
**/
void Application_Error(object sender, EventArgs e)
{
// We clear the response
Response.Clear();

// 获取错误类
Exception exc = Server.GetLastError();

// 检查是否Ajax请求,如果是的话,需要返回JSon结果
if (IsAjaxRequest())
{
Response.Write("JSon结果");
}
else
{
// 单独显示404页面
if (is404Error(exc)) {
Response.Redirect("/ERROR/E404");
}
else
{
#if DEBUG
// 仅在调试阶段显示错误信息页面
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", "/ERROR/DevOnly");
sb.AppendFormat("<input type='hidden' name='message' value='{0}'>",
HttpUtility.UrlEncode(exc.Message));    // 此处必须Encode,否则单引号无法正确显示
sb.AppendFormat("<input type='hidden' name='source' value='{0}'>",
HttpUtility.UrlEncode(exc.Source));    // 此处必须Encode,否则单引号无法正确显示
sb.AppendFormat("<input type='hidden' name='stackTrace' value='{0}'>",
HttpUtility.UrlEncode(exc.StackTrace));    // 此处必须Encode,否则单引号无法正确显示
sb.AppendFormat("<input type='hidden' name='innerException' value='{0}'>",
HttpUtility.UrlEncode(exc.InnerException != null ? exc.InnerException.Message : ""));    // 此处必须Encode,否则单引号无法正确显示

sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");

Response.Write(sb.ToString());

Response.End();
#else
Response.Redirect("/ERROR/");
#endif
}
}

//We clear the error
Server.ClearError();
}

/// <summary>
/// 检查是否属于404错误
/// </summary>
/// <param name="exc"></param>
/// <returns></returns>
private bool is404Error(Exception exc)
{
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
var httpException = (HttpException)exc;
if (httpException.GetHttpCode() == 404)
return true;
}

return false;
}

/// <summary>
/// 检查是否是Ajax请求
/// </summary>
/// <returns></returns>
private bool IsAjaxRequest()
{
//The easy way
bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
|| ((Request.Headers != null)
&& (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

//If we are not sure that we have an AJAX request or that we have to return JSON
//we fall back to Reflection
if (!isAjaxRequest)
{
try
{
//The controller and action
string controllerName = Request.RequestContext.
RouteData.Values["controller"].ToString();
string actionName = Request.RequestContext.
RouteData.Values["action"].ToString();

//We create a controller instance
DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
Controller controller = controllerFactory.CreateController(
Request.RequestContext, controllerName) as Controller;

//We get the controller actions
ReflectedControllerDescriptor controllerDescriptor =
new ReflectedControllerDescriptor(controller.GetType());
ActionDescriptor[] controllerActions =
controllerDescriptor.GetCanonicalActions();

//We search for our action
foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
{
if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
{
//If the action returns JsonResult then we have an AJAX request
if (actionDescriptor.MethodInfo.ReturnType
.Equals(typeof(JsonResult)))
return true;
}
}
}
catch
{

}
}

return isAjaxRequest;
}


在显示错误页面的地方,使用了将Reponse Redirect从Get变为Post的技巧,可以参考以前的文章
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: