在ASP.NET MVC中,进行异常处理变的更为简单。
方法一:重写OnException
在需要进行异常处理的Controller中重写OnException。如果整个程序都需要异常处理,可以先写一个BaseController,其他所有Controller都继承它,然后在BaseController中重写OnException。
1
protected
override
void
OnException(ExceptionContext filterContext)
2 {
3 // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
4 // 通过filterContext.Exception来获取这个异常。
5 string filePath = @"D:\Temp\Exceptions.txt";
6 StreamWriter sw = System.IO.File.AppendText(filePath);
7 sw.Write(filterContext.Exception.Message);
8 sw.Close();
9
10 // 执行基类中的OnException
11 base.OnException(filterContext);
12
13 // 重定向到异常显示页或执行其他异常处理方法
14 Response.Redirect("/");
15}
2 {
3 // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
4 // 通过filterContext.Exception来获取这个异常。
5 string filePath = @"D:\Temp\Exceptions.txt";
6 StreamWriter sw = System.IO.File.AppendText(filePath);
7 sw.Write(filterContext.Exception.Message);
8 sw.Close();
9
10 // 执行基类中的OnException
11 base.OnException(filterContext);
12
13 // 重定向到异常显示页或执行其他异常处理方法
14 Response.Redirect("/");
15}
方法二:添加ActionFilter
如果只是想针对某个Action使用异常处理那就不能重写Controller的OnException了的。但是我们可以先写一个ExceptionLogAttribute。
1
namespace
Snowdream.Demo.MvcExceptionLogging
2 {
3 public class ExceptionLogAttribute:HandleErrorAttribute
4 {
5 public override void OnException(ExceptionContext filterContext)
6 {
7 string filePath = @"D:\Temp\Exceptions.txt";
8 StreamWriter sw = System.IO.File.AppendText(filePath);
9
10
11 sw.Write(filterContext.Exception.Message);
12 sw.Close();
13
14 base.OnException(filterContext);
15
16 filterContext.HttpContext.Response.Redirect("/");
17 }
18 }
19}
20
2 {
3 public class ExceptionLogAttribute:HandleErrorAttribute
4 {
5 public override void OnException(ExceptionContext filterContext)
6 {
7 string filePath = @"D:\Temp\Exceptions.txt";
8 StreamWriter sw = System.IO.File.AppendText(filePath);
9
10
11 sw.Write(filterContext.Exception.Message);
12 sw.Close();
13
14 base.OnException(filterContext);
15
16 filterContext.HttpContext.Response.Redirect("/");
17 }
18 }
19}
20
然后在需要进行异常处理的Action前加上[ExceptionLog],如:
1
[ExceptionLog]
2 public ActionResult Index()
3 {
4 ViewData["Message"] = "Welcome to ASP.NET MVC!";
5
6 return View();
7}
8
2 public ActionResult Index()
3 {
4 ViewData["Message"] = "Welcome to ASP.NET MVC!";
5
6 return View();
7}
8
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-608499/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-608499/