欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ASP.NET页面错误处理及邮件发送简易方案 博客分类: asp.net asp.netasp 

程序员文章站 2024-03-21 22:13:34
...

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

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

3.具体代码

Default.aspx页面

 

Code
html部分:
<body>
    <form. id="form1" runat="server ">
    <div>
   
    </div>
    <asp:DropDownList ID="DropDownList1" runat="server" DataTextField="Name"
        DataValueField="id">
    </asp:DropDownList>
    <asp:Button ID="Button1" runat="server" Text="Button" nClick="Button1_Click" />
    </form>
</body>
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部分:
<body>
    <form. id="form1" runat="server">
    <div style="background-color: #99CCFF; height: 252px;">
        抱歉:发生了错误。
     <div style="background-color:Silver"><asp:Label ID="Label1" runat="server"
            Text="Label"></asp:Label></div>
   
    </div>
    </form>
</body>
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("myaccount@test.com ");
        myMail.To.Add("test@test.com ");
        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