MVC.Net:通过Global.asax捕捉错误
2014-06-22 21:00
274 查看
在MVC.Net中,如果我们想做一个统一的错误处理的模块,有几个选择,一种是通过一个Base Controller来实现,另外一种就是在Global.asax中实现。这里介绍后一种方法。
首先打开Global.asax文件,然后添加如下代码:
在显示错误页面的地方,使用了将Reponse Redirect从Get变为Post的技巧,可以参考以前的文章。
首先打开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的技巧,可以参考以前的文章。
相关文章推荐
- asp.net mvc 错误 global.asax
- ASP.NET通过Global.asax和Timer定时器 定时调用WebService 运行后台代码
- ASP.NET通过Global.asax和Timer定时器 定时调用WebService 运行后台代码
- ASP.NET MVC中的Global.asax文件
- ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常
- 使用Global.asax在ASP.NET中记录错误日志
- ASP.NET使用Global.asax进行全局错误处理
- ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常
- ASP.NET MVC中的Global.asax文件
- asp.net 通过Global.asax 定时执行web应用中的的程序
- asp.net 利用Global.asax 捕获整个解决方案中的异常错误 .
- ASP.NET通过Global.asax和Timer定时器 定时调用WebService 运行后台代码
- Asp.Net MVC中捕捉错误路由并设置默认Not Found页面。
- ASP.NET通过Global.asax和Timer定时器 定时调用WebService 运行后台代码
- ASP.NET通过Global.asax和Timer定时器 定时调用WebService 运行后台代码
- 在ASP.Net MVC 中,如何在Global.asax中配置一个指向Area内部的默认Route
- asp.net mvc 3.0详细笔记__07__项目文件结构详解_Global.asax
- ASP.NET MVC中的Global.asax文件
- net错误日志统一处理 Global.asax
- ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常