ASP.NET MVC 異常處理

來源:互聯網
上載者:User

之前我寫過一篇關於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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.