asp.net中當伺服器出錯時顯示指定的錯誤頁面,同時把錯誤資訊寫入系統記錄檔的探討

來源:互聯網
上載者:User
asp.net|錯誤|伺服器|顯示|頁面 asp.net中當伺服器出錯時顯示指定的錯誤頁面同時把錯誤資訊寫入系統記錄檔的探討

一,在Web.config中填寫出錯時顯示的頁面,可以根據不同的statusCode顯示不同的出錯頁面。
   <customErrors mode="On"  //如果設定為Off則出錯只返回錯誤資訊,不會跳到自己的指定頁面defaultRedirect="/error/customerrorpage.aspx">
    <error statusCode="404" redirect="/error/404Page.aspx"/>
    <error statusCode="403" redirect="/error/403page.aspx"/>
  </customErrors>

二,在Global.asax檔案中添加應用出錯代碼,寫入系統記錄檔
protected void Application_Error(Object sender, EventArgs e)
        {
            Exception LastError = Server.GetLastError();
            String ErrMessage = LastError.ToString();

            String LogName  = "MyLog";
            String Message = "Url " + Request.Path + " Error: " + ErrMessage;

            // Create Event Log if It Doesn't Exist
        
            if (!EventLog.SourceExists(LogName))
            {
                EventLog.CreateEventSource(LogName, LogName);
            }
            EventLog Log = new EventLog();
            Log.Source  = LogName;
            //These are the five options that will display a different icon.
            Log.WriteEntry(Message, EventLogEntryType.Information, 1);
            Log.WriteEntry(Message, EventLogEntryType.Error, 2);
            Log.WriteEntry(Message, EventLogEntryType.Warning, 3);
            Log.WriteEntry(Message, EventLogEntryType.SuccessAudit, 4);
            Log.WriteEntry(Message, EventLogEntryType.FailureAudit, 5);

        }
三,現在你可以進行測試了。
我在Default.aspx.cs中產生一個錯誤,果然跳到預設的錯誤頁面!
private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            try
            {
                int y=0;
                int x=1/y;
            }
            catch (Exception Err)
            {
                throw new Exception("404");//我想產生不同的錯誤,對應web.config中的statusCode,該如何??
                //Err.
            }




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.