1、目录
2、ASP.NET错误捕获的处理发生在三个水平上
2. 1 在类水平上 At the class level
2.1.1 使用try…catch语法块处理异常信息
try { double dVal1 = Convert.ToDouble(txtValue1.Text); double dVal2 = Convert.ToDouble(txtValue2.Text); double result = dVal1 / dVal2; labMessage.Text = txtValue1.Text + "/" + txtValue2.Text; labMessage.Text += "=" + result;}
catch (FormatException ex1) { labMessage.Text = "Please enter a valid number";}
catch (Exception ex2){labMessage.Text = "Unable to compute a value with these values";}
2.2.2 使用try…catch…finnally语法块处理异常信息
try{// Open a database connection// Execute SQL statement}
catch (DbException ex){// Handle database exception}
finally{// Close database connection if it exists}
2.2.3 处理异常的几种策略
- “消化”catch语法块所捕获的异常,并忽略异常执行正常操作
- 在catch代码块中完全处理产生的异常
- 忽略异常而且不捕获这些异常,让其它的类来处理它们
- 捕获异常并重新抛出异常让其它类处理
2. 2 在页面水平上At the page level
protected void Page_Load(object sender, EventArgs e)
{BuggyMethod();
}
private void BuggyMethod()
{// Deliberately throw an exception to simulate// uncaught exceptionthrow new
ApplicationException(
"Your buggy code caused an exception.");}
//use Page_Error Handler to deal with exceptionsprivate void Page_Error(object sender, EventArgs e)
{Exception ex = Server.GetLastError();
Response.Write("<h1>An error has occurred</h1>");Response.Write("<h2>" + ex.Message + "</h2>");
Response.Write("<pre>" + ex.StackTrace + "</pre>");
Context.ClearError();
}
}
2. 3 在应用程序水平上At the application level
有两种方式处理应用程序水平上的异常,一是使用Application_Error事件处理器(event handler); 二是使用ASP.NET错误页面重定向机制(error page redirection mechanism).
2.3.1 Using the Application_Error Handler
Application_Error event handler包括在应用程序的Global.asax文件中
2.3.2 Using Custom Error Pages
3、验证控件
3.1 验证过程ASP.NET Form Validation Process
ASP.NET验证控件及进行客户端验证也进行服务器端验证
3.1.1 客户端验证过程Client-Side Validation Process
3.1.2 服务器端验证过程Server-Side Validation Process
当客户端验证被禁止,而需要进行服务器回传事件的处理是可以使用IsValid来进行判断
protected void btnSubmit_Click(object sender, EventArgs e)
{// Only process if data is validif (IsValid){int quantity = Convert.ToInt32(txtQuantity.Text);int unitCost = 5;int price = quantity * unitCost;labContent.Text = "Price for order is $" + price;}
}
3.2 对象模型
3.3 验证控件的属性Common Validation Properties
3.4 验证消息的显示模式
验证消息的Display属性有三个可能的值:
• None—验证消息不显示.
• Static—不管消息是否出现,在页面上给验证消息预留出消息文本显示的空间
• Dynamic—只有当验证失败,需要显示消息时才分配给消息文本在页面的显示空间,动态显示只有在客户端验证可行时有效
3.5 RequiredFieldValidator Control
RequiredFieldValidator Control主要用在检验文本框是否进行了输入,不要留空字符串,但有时候也用在DropDownList中验证是否选中了选项,例如:
<div>
<asp:DropDownList ID="lstBooks" runat="server">
<asp:ListItem Value="0" Selected="True">Pick a book</asp:ListItem>
<asp:ListItem Value="1">The Republic</asp:ListItem>
<asp:ListItem Value="2">Critique of Judgment</asp:ListItem>
<asp:ListItem Value="3">Theory of Justice</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqBook" runat="server" ControlToValidate="lstBooks"
Text="Please choose a book from the list" InitialValue="0" />
</div>
3.6 ValidationSummary Control
3.6.1 属性
3.7 CompareValidator Control
- 比较表单的值和一个常量
- 验证表单数据的数据类型
- 比较两个控件的值
3.7.1 属性
3.7.2 示例代码
<div>
<p>
Age:<br />
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:CompareValidator ID="compAge" runat="server" ControlToValidate="txtAge" ValueToCompare="18"
Operator="LessThanEqual" SetFocusOnError="true" Text="You are too old to view this site" />
</p>
<p>
Sales Date:<br />
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:CompareValidator ID="compDate" runat="server" ControlToValidate="txtDate" Operator="DataTypeCheck"
Type="Date" Text="Enter a valid date" />
</p>
<p>
Quantity:<br />
<asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
<asp:CompareValidator ID="compQuantity" runat="server" ControlToValidate="txtQuantity"
Operator="DataTypeCheck" Type="Integer" Text="Enter a valid whole number" />
</p>
<p>
Enter Password:<br />
<asp:TextBox ID="txtPass1" runat="server" TextMode="password"></asp:TextBox>
</p>
<p>
Reenter Password:<br />
<asp:TextBox ID="txtPass2" runat="server" TextMode="password"></asp:TextBox>
</p>
<asp:CompareValidator ID="compPass" runat="server" ControlToValidate="txtPass2" Operator="Equal"
ControlToCompare="txtPass1" Text="Passwords must match" />
<p>
<asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
</p>
</div>
3.8 RangeValidator Control
3.9 RegularExpressionValidator Control
正则表达式是一系列符合某个模式的字符。它是一种特殊的语言用来对文本字符串进行匹配和操控。正则表达式由两种类型的字符组成:
literals:是需要进行匹配的字符
metacharacters:用于正则表达式解析使用的特殊的命令字符,经常以”\”开头
示例代码:
3.9.1 使用正则表达式类Using the RegEx Class
使用正则表达式来获取指定页面的<h1>,<h2>, <h3>等标题信息,示例如下
ScrapeHeadings.aspx
<asp:Panel ID="panUrl" runat="server" GroupingText="Search" CssClass="myPanel">
Enter Url:
<asp:TextBox ID="txtUrl" runat="server" Columns="50"></asp:TextBox><br />
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
</asp:Panel>
<p>
</p>
<asp:Panel ID="panHeadings" runat="server" GroupingText="Headings in this Url" CssClass="myPanel" >
<asp:Literal ID="litContent" runat="server" />
</asp:Panel>
ScrapeHeadings.aspx.cs
1: using System;
2: using System.Web;
3: 4: // need to add these
5: using System.Net;
6: using System.Text.RegularExpressions;
7: 8: public partial class ScrapeHeadings : System.Web.UI.Page
9: {10: /// <summary>
11: /// Each time the page loads, empty the literal control
12: /// </summary>
13: protected void Page_Load(object sender, EventArgs e)
14: {15: litContent.Text = "";
16: } 17: 18: /// <summary>
19: /// Event handler for seach button
20: /// </summary>
21: protected void btnSearch_Click(object sender, EventArgs e)
22: {23: // need to trap error in case of unresponsive URL
24: try
25: {26: // use the WebClient class to download content at url into a string
27: WebClient client = new WebClient();
28: string content = client.DownloadString(txtUrl.Text);
29: 30: // match any of the H? tags
31: Regex reg = new Regex(@"<h\d>.+</h\d>", RegexOptions.IgnoreCase);
32: 33: // get a collection of all the matches
34: MatchCollection mc = reg.Matches(content); 35: 36: // iterate through the collection of matches
37: foreach (Match m in mc)
38: {39: // HTML encode the tag and display in literal
40: litContent.Text += HttpUtility.HtmlEncode(m.Value) + "<br/>";
41: } 42: }43: catch
44: {45: litContent.Text = "Could not connect to " + txtUrl.Text;
46: } 47: } 48: }3.9.2 正则表达式及其安全性Regular Expressions and Security
一种保护网站免受注入式攻击的方式是使用正则表达式来控制所有文本型输入格式。注入式攻击是利用非控制性的文本输入来插入以下非法的SQL或者JavaScript代码。正则表达式验证控件可以限定输入文本的长度,格式等。
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="regName" runat="server"
ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,50}"
Text="Enter a valid name" />
//If the input is coming in from a nonform field source, such as a cookie or querystring, you can use the RegEx class to perform the same type of check.string source = (string)Cookie["someValue"];
RegEx reg = new RegEx("^[a-zA-Z'.\s]{1,50}");
if ( ! reg.IsMatch(source) ){// Some type of error handling would go here}






















浙公网安备 33010602011771号