首页 > Linux操作系统 > Linux操作系统 > ASP.NET MVC 异常处理
在ASP.NET MVC中,进行异常处理变的更为简单。
方法一:重写OnException
在需要进行异常处理的Controller中重写OnException。如果整个程序都需要异常处理,可以先写一个BaseController,其他所有Controller都继承它,然后在BaseController中重写OnException。
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);
// 重定向到异常显示页或执行其他异常处理方法
Response.Redirect("/");
}
方法二:添加ActionFilter
如果只是想针对某个Action使用异常处理那就不能重写Controller的OnException了的。但是我们可以先写一个ExceptionLogAttribute。
namespace Snowdream.Demo.MvcExceptionLogging
{
public class ExceptionLogAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
string filePath = @"D:\Temp\Exceptions.txt";
StreamWriter sw = System.IO.File.AppendText(filePath);

sw.Write(filterContext.Exception.Message);
sw.Close();
base.OnException(filterContext);
filterContext.HttpContext.Response.Redirect("/");
}
}
}
然后在需要进行异常处理的Action前加上[ExceptionLog],如:
[ExceptionLog]
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-608499/ ,如需转载,请注明出处,否则将追究法律责任。