在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. Akka源码分析-Extension

    一个设计优秀的工具或框架,应该都有一个易用.强大的插件或扩展体系,akka也不例外. akka的扩展方法非常简单,因为只涉及到两个组件:Extension. ExtensionId.其中Extensi ...

  2. Android常用的Dialog对话框用法

    Android的版本有很多通常开发的时候对话框大多数使用自定义或是 Google提供的V4, V7 兼容包来开发保持各个版本的对话框样式统一,所以这里使用的是V7 包里的AlertDialog. im ...

  3. 努比亚(nubia) Z18 mini NX611J 解锁BootLoader 并刷入recovery ROOT

    努比亚(nubia)  Z18 mini NX611J解锁BootLoader 并刷入recovery ROOT 工具下载链接:https://pan.baidu.com/s/1toU-mTR9FNE ...

  4. postgres外部表如何修改源码适配pg升级

    postgres中外部表的应用如下: 但是许多在github上的fdw开源代码都是基于9.3以及9.4版本开发,原作者没有随着pg的版本升级而将外部表扩展升级,那只能靠自己去手动修改源码来让这些扩展能 ...

  5. Android Studio 快捷键整理

    Alt+回车 导入包,自动修正 Ctrl+N   查找类Ctrl+Shift+N 查找文件Ctrl+Alt+L  格式化代码Ctrl+Alt+O 优化导入的类和包Alt+Insert 生成代码(如ge ...

  6. Python语言之函数

    1.函数的定义与调用 def function(x): print("function(%s)"%x) function("hello") #call the ...

  7. 关于Python中的类普通继承与super函数继承

    关于Python中的类普通继承与super函数继承 1.super只能用于新式类 2.多重继承super可以保公共父类仅被执行一次 一.首先看下普通继承的写法 二.再看看super继承的写法 参考链接 ...

  8. seam remote 返回的map结构

    map结构的数据,js接收到的结构是elements下面的一个 [ {key:***,value:***}, {key:***,value:***} ] 这样子的集合,需要经过下面代码的转换才能重新变 ...

  9. Oracle 函数总结

    <1>=========================返回 String,其中包含有与指定的字符代码相关的字符======================== 函      数:< ...

  10. Node.js 命令行程序开发教程 ---------http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html

    五.yargs 模块 shelljs 只解决了如何调用 shell 命令,而 yargs 模块能够解决如何处理命令行参数.它也需要安装. $ npm install --save yargs yarg ...