ASP.NET 错误处理
ASP.NET 中的错误处理包括三个方面:
Tracing-在页面级别或应用程序级别跟踪程序执行。
Error handling-在页面级别或应用程序级别处理标准错误或自定义错误。
Debugging-单步执行程序,设置断点以分析代码
在本章中,我们将讨论跟踪和错误处理,在本章中,我们将讨论调试。
要理解这些概念,请创建以下示例应用程序。它有一个标签控件、一个下拉列表和一个链接。下拉列表加载名言数组列表,所选名言显示在下面的标签中。它还有一个超链接,指向一个不存在的链接。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" %>
<!DOCTYPE html public "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Tracing, debugging and error handling
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblheading" runat="server" Text="Tracing, Debuggin and Error Handling">
</asp:Label>
<br /> <br />
<asp:DropDownList ID="ddlquotes" runat="server" AutoPostBack="True" onselectedindexchanged="ddlquotes_SelectedIndexChanged">
</asp:DropDownList>
<br /> <br />
<asp:Label ID="lblquotes" runat="server">
</asp:Label>
<br /> <br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="mylink.htm">Link to:</asp:HyperLink>
</div>
</form>
</body>
</html>
文件背后的代码:
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[,] quotes =
{
{"Imagination is more important than Knowledge.", "Albert Einsten"},
{"Assume a virtue, if you have it not" "Shakespeare"},
{"A man cannot be comfortable without his own approval", "Mark Twain"},
{"Beware the young doctor and the old barber", "Benjamin Franklin"},
{"Whatever begun in anger ends in shame", "Benjamin Franklin"}
};
for (int i=0; i<quotes.GetLength(0); i++)
ddlquotes.Items.Add(new ListItem(quotes[i,0], quotes[i,1]));
}
}
protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlquotes.SelectedIndex !=-1)
{
lblquotes.Text = String.Format("{0}, Quote: {1}", ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue);
}
}
}
Tracing
要启用页面级跟踪,您需要修改 Page 指令并添加 Trace 属性,如下所示:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="errorhandling._Default" Trace ="true" %>
现在当你执行文件时,你会得到跟踪信息:
它在顶部提供以下信息:
会话 ID
状态代码
请求时间
请求类型
请求和响应编码
服务器发送的状态码,每次请求页面时都会显示错误的名称和时间(如果有的话)。下表显示了常见的 HTTP 状态代码:
数量 |
说明 |
信息(100-199) |
100 |
Continue |
101 |
Switching protocols |
Successful (200 - 299) |
200 |
OK |
204 |
No content |
重定向(300-399) |
301 |
Moved permanently |
305 |
Use proxy |
307 |
Temporary redirect |
客户端错误 (400-499) |
400 |
Bad request |
402 |
Payment required |
404 |
Not found |
408 |
Request timeout |
417 |
Request timeout |
服务器错误 (500-599) |
500 |
Internal server error |
503 |
Service unavailable |
505 |
HTTP version not supported |
在顶级信息下,有 Trace 日志,提供页面生命周期的详细信息。它提供自页面初始化以来经过的时间(以秒为单位)。
下一部分是控件树,它以分层的方式列出页面上的所有控件:
会话和应用程序状态摘要、cookie 和标头集合中的最后一个,后跟所有服务器变量的列表。
Trace 对象允许您向跟踪输出添加自定义信息。它有两种方法来实现这一点:Write 方法和 Warn 方法。
更改 Page_Load 事件处理程序以检查 Write 方法:
protected void Page_Load(object sender, EventArgs e)
{
Trace.Write("Page Load");
if (!IsPostBack)
{
Trace.Write("Not Post Back, Page Load");
string[,] quotes =
.......................
}
}
运行观察效果:
要检查Warn方法,让我们在selected index changed事件处理程序中强行输入一些错误代码:
try
{
int a = 0;
int b = 9 / a;
}catch (Exception e)
{
Trace.Warn("UserAction", "processing 9/a", e);
}
Try-Catch 是一种 C# 编程结构。 try 块保存可能会或可能不会产生错误的任何代码,而 catch 块会捕获错误。当程序运行时,它会在跟踪日志中发送警告。
应用程序级别跟踪适用于网站中的所有页面。它是通过将以下代码行放入 web.config 文件来实现的:
<system.web>
<trace enabled="true" />
</system.web>
错误处理
虽然 ASP.NET 可以检测所有运行时错误,但仍然可能存在一些细微的错误。通过跟踪观察错误是为了开发者,而不是为了用户。
因此,为了拦截此类事件,您可以在应用程序的 web.config 文件中添加错误处理设置。它是应用程序范围的错误处理。例如,您可以在 web.config 文件中添加以下几行:
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
<configuration>
部分具有可能的属性:
Mode :它启用或禁用自定义错误页面。它具有三个可能的值:
On :显示自定义页面。
Off : 显示 ASP.NET 错误页面(黄页)
remoteOnly:向客户端显示自定义错误,在本地显示 ASP.NET 错误。
defaultRedirect :它包含要在出现未处理错误时显示的页面的 URL。
为了针对不同类型的错误放置不同的自定义错误页面,使用
子标签,根据错误的状态代码指定不同的错误页面。
要实现页面级错误处理,可以修改 Page 指令:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %>
因为 ASP.NET 调试本身就是一个重要的主题,所以我们将在下一章单独讨论。