随笔 - 59  文章 - 0  评论 - 340  阅读 - 34万 

之前我写过一篇关于ASP.NET全局异常处理的文章(http://www.cnblogs.com/snowdream/archive/2008/07/03/1234402.html)。在ASP.NET MVC中,进行异常处理变的更为简单。

方法一:重写OnException
在需要进行异常处理的Controller中重写OnException。如果整个程序都需要异常处理,可以先写一个BaseController,其他所有Controller都继承它,然后在BaseController中重写OnException。

复制代码
 1protected 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}
复制代码

 

方法二:添加ActionFilter
如果只是想针对某个Action使用异常处理那就不能重写Controller的OnException了的。但是我们可以先写一个ExceptionLogAttribute。

复制代码
 1namespace 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
复制代码

然后在需要进行异常处理的Action前加上[ExceptionLog],如:

复制代码
1[ExceptionLog]
2public ActionResult Index()
3{
4    ViewData["Message"= "Welcome to ASP.NET MVC!";
5
6    return View();
7}

8
复制代码

示例下载

本文适用于 ASP.NET MVC 1.0
posted on   Magic.Z  阅读(7033)  评论(9编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2008-03-01 IIS7的HTTP 500.19错误
点击右上角即可分享
微信分享提示