ASP.NET Tutorial/Development/Server class
Содержание
- 1 Demonstration of Page_Error Handler
- 2 An error has occurred
- 2.1 " + ex.Message + "
- 2.2 Forward the user to the information page, with the query string data (#)
- 2.3 Server.Execute
- 2.4 Server.GetLastError()
- 2.5 Server.HtmlDecode
- 2.6 Server.HtmlEncode
- 2.7 Server.MachineName
- 2.8 Server.MapPath
- 2.9 Server.ScriptTimeout
- 2.10 Server.Transfer
- 2.11 Server.UrlDecode
- 2.12 Server.UrlEncode
- 2.13 Server.UrlPathEncode
- 2.14 text generated by Execute can be embedded in the main response or cached in a writer object
- 2.15 Use Server.HtmlEncode to encode HTML tags (C#)
- 3 Properly encoded:
- 4 Incorrectly encoded:
Demonstration of Page_Error Handler
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="PageExceptionTest" %> <!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>Demonstration of Page_Error Handler</title>
</head> <body>
<form id="form1" runat="server"> Demonstration of Page_Error Handler. This markup will never be displayed. </form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class PageExceptionTest : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { BuggyMethod(); } private void BuggyMethod() { throw new ApplicationException("Your buggy code caused an exception."); } private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError();Response.Write("
An error has occurred
"); Response.Write("" + ex.Message + "
"); Response.Write("" + ex.StackTrace + "");
Context.ClearError(); }
}</source>
Forward the user to the information page, with the query string data (#)
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="QueryStringSender" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:ListBox ID="lstItems" runat="server" Height="155px" Width="165px"></asp:ListBox>
<asp:CheckBox ID="chkDetails" runat="server" Text="Show full details" />
<asp:Button ID="cmdGo" runat="server" OnClick="cmdGo_Click" Text="View Information" Width="165px" />
<asp:Label ID="lblError" runat="server" EnableViewState="False"></asp:Label>
</form>
</body> </html>
File: Default.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class QueryStringSender : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { lstItems.Items.Add("A"); lstItems.Items.Add("B"); lstItems.Items.Add("C"); lstItems.Items.Add("D"); lstItems.Items.Add("F"); } } protected void cmdGo_Click(object sender, EventArgs e) { if (lstItems.SelectedIndex == -1) { lblError.Text = "You must select an item."; } else { string url = "NextPage.aspx?"; url += "Item=" + Server.UrlEncode(lstItems.SelectedItem.Text) + "&"; url += "Mode=" + chkDetails.Checked.ToString(); Response.Redirect(url); } }
}
File: NextPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NextPage.aspx.cs" Inherits="QueryStringRecipient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label ID="lblInfo" runat="server" EnableViewState="False" ></asp:Label>
</form>
</body> </html>
File: NextPage.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class QueryStringRecipient : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { lblInfo.Text = "Item: " + Request.QueryString["Item"]; lblInfo.Text += "
Show Full Record: "; lblInfo.Text += Request.QueryString["Mode"]; }
}</source>
Server.Execute
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Executing Another Page and Returning its Output</title> <script runat="server"> Sub Execute() Dim Url As String = "CreateObject.aspx" Dim sw As New System.IO.StringWriter Server.Execute(Url, sw) Response.Write("Request output:
" & sw.ToString()) End Sub </script>
</head> <body> <% Execute %> </body> </html></source>
Server.GetLastError()
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Examining the Last Error</title> <script runat="server"> Sub CauseError(sender As Object, e As EventArgs) Dim x, y, z As Integer y = 1 z = 0 x = y / z End Sub Sub Page_Error(Source As Object, E As EventArgs) Dim LastError As Exception Dim ErrMessage As String LastError = Server.GetLastError() If Not LastError Is Nothing Then ErrMessage = LastError.Message Else ErrMessage = "No Errors" End If Response.Write("Last Error = " & ErrMessage & "
") Server.ClearError() End Sub </script>
</head> <body>
<form runat="server">
Cause an Error to Occur...
<asp:button text="CauseError" OnClick="CauseError" runat="server"/> </form>
</body> </html></source>
Server.HtmlDecode
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Decoding Encoded HTML Strings</title> <script runat="server"> Sub HtmlDecode() Dim StrToDecode As String Dim StrToReturn As String StrToDecode = "<p>Hello, World!</p>" StrToReturn = Server.HtmlDecode(StrToDecode) Response.Write(StrToReturn) End Sub </script>
</head> <body> <% HtmlDecode %> </body> </html></source>
Server.HtmlEncode
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Encoding HTML Strings</title> <script runat="server"> Sub HtmlEncode() Dim StrToEncode As String Dim StrToReturn As String StrToEncode = "<%@ Page Language=""VB"" %>" StrToReturn = Server.HtmlEncode(StrToEncode) Response.Write(StrToReturn) End Sub </script>
</head> <body> <% HtmlEncode %> </body> </html></source>
Server.MachineName
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Accessing the MachineName Property</title> <script runat="server"> Sub GetMachineName() Dim ServerName As String ServerName = Server.MachineName Response.Write("The name of the server is " & ServerName & ".
") End Sub </script>
</head> <body> <% GetMachineName %> </body> </html></source>
Server.MapPath
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Determining a Physical Path</title> <script runat="server"> Sub MapPath() Dim RelativePath As String Dim PhysicalPath As String RelativePath = "HtmlEncode.aspx" PhysicalPath = Server.MapPath(RelativePath) Response.Write(PhysicalPath) End Sub </script>
</head> <body> <% MapPath %> </body> </html></source>
Server.ScriptTimeout
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Accessing and Modifying the ScriptTimeout Property</title> <script runat="server"> Sub GetScriptTimeout() Dim Timeout As String "Server.ScriptTimeout = 120 Timeout = Server.ScriptTimeout Response.Write("The current ScriptTimeout value is " & Timeout & ".
") End Sub </script>
</head> <body> <% GetScriptTimeout %> </body> </html></source>
Server.Transfer
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Transferring Control to Another Page</title> <script runat="server"> Sub Transfer() Dim Url As String = "CreateObject.aspx" Server.Transfer(Url) Response.Write("This code will never be executed!") End Sub </script>
</head> <body> <% Transfer %> </body> </html></source>
Server.UrlDecode
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Decoding Encoded URL Strings</title> <script runat="server"> Sub UrlDecode() Dim StrToDecode As String Dim StrToReturn As String StrToDecode = Request.QueryString("StrToDecode") StrToReturn = Server.UrlDecode(StrToDecode) Response.Write(StrToReturn) End Sub </script>
</head> <body> <% UrlDecode %> </body> </html></source>
Server.UrlEncode
<source lang="csharp">
<%@ Page Language="VB" %> <html>
<head> <title>URLEncoding</title> <script runat="server"> Sub Page_Load() If IsPostBack Response.Write(Server.UrlEncode(Request.Form("name"))) End If End Sub </script> </head>
<body>
<form id="form1" action="Default.aspx" method="POST" runat="server">
Name:
<input type="text" id="name" runat="server"> <input type="submit" runat="server"> </form>
</body> </html></source>
Server.UrlPathEncode
<source lang="csharp">
<%@ Page Language="VB" %> <html> <head>
<title>Encoding URL Strings</title> <script runat="server"> Sub UrlPathEncode() Dim StrToEncode As String Dim StrToReturn As String StrToEncode = "UrlPathEncode.aspx?Arg=foo" StrToReturn = Server.UrlPathEncode(StrToEncode) Response.Write("<a href=""" & StrToReturn & """>" & StrToReturn & "</a>") End Sub </script>
</head> <body> <% UrlPathEncode %> </body> </html></source>
text generated by Execute can be embedded in the main response or cached in a writer object
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Testing Server.Execute</title>
</head> <body>
<form id="form1" runat="server"> <asp:Label runat="server" ID="Label1"></asp:Label> </form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.IO; using System.Web; using System.Text; using System.Web.UI; using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { StringBuilder builder = new StringBuilder();builder.Append("Response generated before Execute is called
");
StringWriter writer = new StringWriter(); Server.Execute("child.aspx", writer); builder.Append(writer.ToString());builder.Append("
Response generated after the call to Execute.");
Label1.Text = builder.ToString(); }
} File: child.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Child" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>child.aspx</title>
</head> <body>
<form id="form1" runat="server">
</form>
</body> </html> File: child.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; public partial class Child : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Response.Write("Response generated by child.aspx"); }
}</source>
Use Server.HtmlEncode to encode HTML tags (C#)
<source lang="csharp">
File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="HtmlEncodeTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form ID="form1" runat="server">
Properly encoded:
<div ID="ctrl2" runat="server"/>
Incorrectly encoded:
<div ID="ctrl1" runat="server"/>
</form>
</body> </html>
File: Default.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class HtmlEncodeTest : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { ctrl1.InnerHtml = "To bold text use the tag."; ctrl2.InnerHtml = "To <b>bold text use the " + Server.HtmlEncode("") + " tag."; }
}</source>
Use Server.MapPath() to load the file in the current directory (VB.net)
<source lang="csharp">
<%@ Page Language="VB" %> <%@ Import Namespace="System.Xml" %> <script runat=server>
sub Page_Load(Sender as Object, e as EventArgs) dim reader as XMLTextReader try reader = new XMLTextReader(Server.MapPath("books.xml")) While reader.Read() Response.Write("<b>" & reader.Name & " " & _ reader.Value & "
") End While catch ex as Exception Response.Write("Error accessing XML file") finally reader.close end try end sub
</script> <html><body> </body></html> File: books.xml <?xml version="1.0"?> <bookstore>
<book genre="asdf"> <title>asdf</title> <author> <first-name>asdf</first-name> <last-name>asdf</last-name> </author> <price>asdf</price> </book> <book genre="asdf"> <title>asdf</title> <author> <first-name>asdf</first-name> <last-name>asdf</last-name> </author> <price>asdf</price> </book> <book genre="asdf"> <title>asdf</title> <author> <first-name>asdf</first-name> <last-name>asdf</last-name> </author> <price>asdf</price> </book>
</bookstore></source>
Use Server.Transfer to transfer action to another aspx file (C#)
<source lang="csharp">
File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="CrossPage1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>CrossPage1</title>
</head> <body>
<form id="form1" runat="server" >
First Name: <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
Last Name: <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<asp:Button runat="server" ID="cmdPost" PostBackUrl="NextPage.aspx" Text="Cross-Page Postback" />
<asp:Button runat="server" ID="cmdTransfer" Text="Manual Transfer" OnClick="cmdTransfer_Click" Visible="False" />
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CrossPage1 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["err"] != null) Page.Validate(); }
protected void cmdTransfer_Click(object sender, EventArgs e) { Server.Transfer("NextPage.aspx", true); } public string FullName { get { return txtFirstName.Text + " " + txtLastName.Text; } }
}
File: NextPage.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NextPage.aspx.cs" Inherits="CrossPage2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<title>Untitled Page</title>
</head> <body>
<form id="form1" runat="server" >
</form>
</body> </html>
File: NextPage.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CrossPage2 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { if (PreviousPage != null) { lblInfo.Text = "You came from a page titled " + PreviousPage.Title + "
"; CrossPage1 prevPage = PreviousPage as CrossPage1; if (prevPage != null) { lblInfo.Text += "You typed in this: " + prevPage.FullName + "
"; } } }
}</source>