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

最新文章

  1. 如何分析解读systemstat dump产生的trc文件
  2. td:first-child 伪类 匹配第一个 匹配第一个 &lt;td&gt; 元素
  3. 解决ScrollView嵌到listView冲突问题
  4. 让MyEclipse2013兼容Retina屏幕
  5. 在Myeclipse中移除项目对Hibernate的支持
  6. Blot消息处理者
  7. PHP之路——PHPStudy虚拟主机
  8. 液晶顯示器 LCD (Liquid Crystal Disply )
  9. Single Number,Single Number II
  10. Swift - 将表格UITableView滚动条移动到底部
  11. 【Android进阶】获取Android软件的版本信息
  12. Sencha Touch vs jQuery Mobile
  13. jQuery学习之旅 Item7 区别this和$(this)
  14. js获取今天是星期几
  15. SE Springer小组之《Spring音乐播放器》需求分析说明书一
  16. Python 列表 extend() 方法
  17. substring_index 用法
  18. C#(wpf)迷你词典
  19. python16_day19【Django_抽屉项目】
  20. VS2013安装部署过程详解

热门文章

  1. 通过类库ChineseChar实现将汉字转化为拼音
  2. [Apple开发者帐户帮助]九、参考(2)撤销特权
  3. CF 436D 最小生成树
  4. PHP电影小爬虫(2)
  5. python导入包出错:ImportError: No module named XXXXX
  6. 使用A*寻路小记
  7. 给定的逗号分隔的数字字符串转换为Table
  8. python--9、进程及并发知识
  9. ubuntu上Hadoop三种运行模式的部署
  10. 微信自定义分享功能实现Tips