ASP.NET页面错误处理及邮件发送简易方案

阅读更多

1包含页面:Default.aspx,Error.aspx

2.思路:Global.asax页面负责捕捉系统中除去try以外发生的页面错误。并将错信息发送给Error.aspx页面。Error.aspx页面负责显示错误信息,并将错误信息发送到指定邮箱。

3.具体代码

Default.aspx页面

 

Code
html部分:

    server ">
   


   
   

            DataValueField="id">
   

   
   

cs部分:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id",typeof(string)));
            dt.Columns.Add(new DataColumn("name", typeof(string)));

            dt.Rows.Add(dt.NewRow());
            dt.Rows[0][0] = "1";
            dt.Rows[0][1] = "1";
            this.DropDownList1.DataSource = dt;
            this.DropDownList1.DataBind();

        }
    }
 protected void Button1_Click(object sender, EventArgs e)
    {
        this.DropDownList1.SelectedValue = "fff";
    }

Global.asax代码:

Code
<%@ Import Namespace ="System.Web" %>
 void Application_Error(object sender, EventArgs e)
    {
        Exception  LastError = Server.GetLastError();
        if (LastError != null)
            Response.Redirect("error.aspx?error="+LastError.InnerException.ToString().Replace("\r\n",""));
    }

Error.aspx代码:

 

Code
html部分:

   
   


        抱歉:发生了错误。
    
            Text="Label">

   
   

   

cs部分:

添加命名空间:

using System.Net.Mail;
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request["error"] != null && Request["error"].Length > 0)
            {
                this.Label1.Text = Request["error"];
                SendMail(Request["error"]);
            }
        }
    }
 public void SendMail(string body)
    {
        MailMessage myMail = new MailMessage();
       
        myMail.From = new MailAddress("[email protected] ");
        myMail.To.Add("[email protected] ");
        myMail.Subject = "Error";
        myMail.Priority = MailPriority.Normal;
        myMail.BodyEncoding = System.Text.Encoding.UTF8;
        myMail.Body = body;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "mail";
        try
        {
            smtp.Send(myMail);
        }
        catch (SmtpException ex)
        {
            this.Label1.Text = "邮件发送失败。\r\n"+ex.Message;
        }

    }

 

至此,系统即可实现错误捕捉显示,及邮件发生功能。

你可能感兴趣的:(asp.net,asp)