在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() == )
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的技巧,可以参考以前的文章

MVC.Net:通过Global.asax捕捉错误的更多相关文章

  1. ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常

    在ASP.NET MVC中,通过应用程序生命周期中的Application_Error事件可以捕获到网站引发的所有未处理异常.本文作为学习笔记,记录了使用Global.asax文件的Applicati ...

  2. ASP.NET MVC中的Global.asax文件

    1.global.asax文件概述 global.asax这个文件包含全局应用程序事件的事件处理程序.它响应应用程序级别和会话级别事件的代码. 运行时, Global.asax 将被编译成一个动态生成 ...

  3. MVC中 global.asax

    MVC框架下 global.asax 页面的事件 这些事件被触发的 顺序是: Application_BeginRequest Application_AuthenticateRequest Appl ...

  4. 全局应用程序类(Global.asax)

     注:该部分参考的园区的“积少成多”的 <ASP.NET MVC中的Global.asax文件> . 1.Global.asax文件介绍 global.asax这个文件包含全局应用程序事件 ...

  5. 在Asp.Net的Global.asax中Application_Error跳转到自定义错误页无效的解决办法

    在开发Asp.Net系统的时候,我们很多时候希望系统发生错误后能够跳转到一个自定义的错误页面,于是我们经常会在Global.asax中的Application_Error方法中使用Response.R ...

  6. Asp.net MVC Global.asax文件

    global.asax文件概述 global.asax这个文件包含全局应用程序事件的事件处理程序.它响应应用程序级别和会话级别事件的代码. 运行时, Global.asax 将被编译成一个动态生成的 ...

  7. 在ASP.Net MVC 中,如何在Global.asax中配置一个指向Area内部的默认Route

    ASP.Net MVC 中配置Route的时候可以设置一个默认的Route. 比如我要在输入http://localhost的时候默认进入http://localhost/home/index.可以在 ...

  8. 【转】asp.net 利用Global.asax 捕获整个解决方案中的异常错误

    之前做项目的时候都是在每个页面中处理这不同的异常信息,一个页面数下来,很多个try{}catch{}语句块,令整个代码结构有些不够美观. 今天看到一篇帖子,是关于利用全局应用程序类来帮忙获取异常信息, ...

  9. asp.net mvc global.asax文件详解

    一.文件概述 global.asax这个文件包含全局应用程序事件的事件处理程序.它响应应用程序级别和会话级别事件的代码. 运行时, Global.asax 将被编译成一个动态生成的 .NET Fram ...

随机推荐

  1. BZOJ 2300凸包+离线

    思路: 倒着加显然吧  动态维护这个凸包就好了 //By SiriusRen #include <bits/stdc++.h> using namespace std; ; int n,m ...

  2. ORACLE SEQUENCE用法(转)

    ORACLE SEQUENCE用法 在oracle中sequence就是序号,每次取的时候它会自动增加.sequence与表没有关系. 1.Create Sequence     首先要有CREATE ...

  3. UE4源码版食用要记

    UE4源码版和预编译版不能共享工程,这和插件版是一样的. 一般来说我都是在VS中生成编辑器,于编辑器中添加新类,VS中编辑代码. 编译引擎的时候编译配置使用的是devepolmenteditor.开发 ...

  4. C#学习-处理Excel

    首先先了解下一个Excel文件的组成 1.一个Excel包含多个工作表(Sheet) 2.一个工作表(Sheet)包含多行(Row) 3.一行(Row)包含多个单元格(Cell)   如何判断一个单元 ...

  5. Python随笔-快排

    def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def part(arr, beg, end): : return b ...

  6. [ HAOI 2008 ] 玩具取名

    \(\\\) \(Description\) 在一个只有\(W,I,N,G\)的字符集中,给出四个字符的若干映射,每个映射为一个字符映射到两个字符,现给你一个假定由一个字符经过多次映射产生的字符串,问 ...

  7. 最容易理解的CSS的position教程——十步图解CSS的position

    CSS的positon,我想做为一个Web制作者来说都有碰到过,但至于对其是否真正的了解呢?那我就不也说了,至少我自己并不非常的了解其内核的运行.今天在Learn CSS Positioning in ...

  8. android fragment轻松监听返回键/Fragment中的popupwindow响应返回键隐藏

    现在的开发我们基本上都是一个主activity中放多个fragment,点击返回按钮的时候,直接退出主activity,但是我们在fragment中经常会弹出例如popupWindow这样的布局,用户 ...

  9. Echarts 出现不明竖线解决方案

    Echarts出现了不明竖线,百思不得其解.去查相应的解决方案也没有找到. 后来自己点来点去,突然感觉像是上一个Echarts遗留的. 然后去Echarts官网看到了 clear()方法,这个方法可以 ...

  10. PHP开发之旅-表单验证

    一.创建表单 <form name = "login" method = "post" action="contact.php?action=l ...