ASP.NET MVC3 异常处理

1.设置web.config
Web.config中设置CustomError CustomError定义自动处理异常的行为,如下所示:
<customErrors mode="On" defaultRedirect="~/Error/NotFound
"> <error statusCode="404" redirect="~/Error/NotFound" /> </customErrors> Mode的值可以是Off、On、RemoteOnly,不同的值定义研发阶段或产品发布后的行为。 Mode值的使用场景: On:开启自定义错误处理。 Off:关闭自定义错误处理,当发生异常时,就会看到ASP.NET的黄页信息。 RemoteOnly:如果在服务器上运行程序(http://localhost),当发生异常时,不会看到自定义异常信息,如果通过其他机器访问该程序,会看到自定义异常信息。该选项常用于开发人员调试程序,如果出现异常,开发人员可以通过本地访问来查看异常详细信息,而远程访问的用户看到的是自定义的异常。

2.添加错误错误提示页面
添加 ErrorController 控制器,在控制器里添加
NotFound 方法.
添加对应视图

异常处理时执行其他功能的方法:

 

1、重写Controller的OnException方法

如果我们不仅仅在出现异常时显示自定义的错误页面,需要记录错误日志,那么可以通过继承Controller类并重些OnException方法实现。如果我们MVC程序的所有Controller都需要记录日志,可以创建一个BaseController,重写OnExcetion方法,然后其他需要记录日志的Controller继承BaseController即可。例如:

  public class BaseController : Controller

  {

        protected override void OnException(ExceptionContext filterContext)

        {
            // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
            // 通过filterContext.Exception来获取这个异常。
            string filePath = @"D:\Temp\Exceptions.txt";
            StreamWriter sw = System.IO.File.AppendText(filePath);
            sw.Write(filterContext.Exception.Message);
            sw.Close();
 
            // 执行基类中的OnException
            base.OnException(filterContext);

 }

那么其他继承自BaseController的Controller就会实现记录错误日志的功能。

 

2、创建FilterAttribute

通过FilterAttribute,并把它添加到全局过滤器集合中就可以提供给整个应用程序使用,如果只需要在某几个Action中使用,可以在Controller的Action中添加此特性。

 

Filter定义如下:

 public class LogExceptionFilterAttribute : FilterAttribute, IExceptionFilter

{
    public void OnException(ExceptionContext filterContext)
    {
        // 添加记录日志代码
    }
}

 

如果要应用给所有的Controller的所有Action,在Global.asax.cs中实现下面代码即可:

 

 

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new LogExceptionFilterAttribute());
    filters.Add(new HandleErrorAttribute());
}
  

或者给只需要使用此特性的Controller或Action添加 :

 

 

 

[LogExceptionFilter()]
public ActionResult About()
{
    throw new Exception("出错.");
}


posted on 2012-04-10 20:03  woshilee  阅读(289)  评论(1)    收藏  举报

导航