MVC.Net:通过Global.asax捕捉错误
2024-08-25 05:40:07
在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的技巧,可以参考以前的文章。
最新文章
- 如何分析解读systemstat dump产生的trc文件
- td:first-child 伪类 匹配第一个 匹配第一个 <;td>; 元素
- 解决ScrollView嵌到listView冲突问题
- 让MyEclipse2013兼容Retina屏幕
- 在Myeclipse中移除项目对Hibernate的支持
- Blot消息处理者
- PHP之路——PHPStudy虚拟主机
- 液晶顯示器 LCD (Liquid Crystal Disply )
- Single Number,Single Number II
- Swift - 将表格UITableView滚动条移动到底部
- 【Android进阶】获取Android软件的版本信息
- Sencha Touch vs jQuery Mobile
- jQuery学习之旅 Item7 区别this和$(this)
- js获取今天是星期几
- SE Springer小组之《Spring音乐播放器》需求分析说明书一
- Python 列表 extend() 方法
- substring_index 用法
- C#(wpf)迷你词典
- python16_day19【Django_抽屉项目】
- VS2013安装部署过程详解