1 page included: default. aspx, error. aspx
2. Idea: The Global. asax page is used to capture page errors other than try in the system. And send the error message to the error. ASPX page. The error. ASPX page displays the error information and sends the error information to the specified mailbox.
3. Specific Code:
Default. aspx page
Code
HTML section:
<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" onclick = "button#click"/>
</Form>
</Body>
CS section:
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 button#click (Object sender, eventargs E)
{
This. dropdownlist1.selectedvalue = "fff ";
}
Global. asax code:
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:
Code
HTML section:
<Body>
<Form ID = "form1" runat = "server">
<Div style = "background-color: #99 CCFF; Height: 252px;">
Sorry: An error occurred.
<Div style = "background-color: Silver"> <asp: Label id = "label1" runat = "server"
TEXT = "label"> </ASP: Label> </div>
</Div>
</Form>
</Body>
CS section:
Add a namespace:
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 = "failed to send the email. \ R \ n "+ ex. message;
}
}
At this point, the system can capture errors and send emails.