ASP.NET Tutorial/Development/Server class
Версия от 15:30, 26 мая 2010; (обсуждение)
Содержание
- 1 Demonstration of Page_Error Handler
- 2 Forward the user to the information page, with the query string data (#)
- 3 Server.Execute
- 4 Server.GetLastError()
- 5 Server.HtmlDecode
- 6 Server.HtmlEncode
- 7 Server.MachineName
- 8 Server.MapPath
- 9 Server.ScriptTimeout
- 10 Server.Transfer
- 11 Server.UrlDecode
- 12 Server.UrlEncode
- 13 Server.UrlPathEncode
- 14 text generated by Execute can be embedded in the main response or cached in a writer object
- 15 Use Server.HtmlEncode to encode HTML tags (C#)
- 16 Use Server.MapPath() to load the file in the current directory (VB.net)
- 17 Use Server.Transfer to transfer action to another aspx file (C#)
Demonstration of Page_Error Handler
<%@ 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("<h1>An error has occurred</h1>");
Response.Write("<h2>" + ex.Message + "</h2>");
Response.Write("<pre>" + ex.StackTrace + "</pre>");
Context.ClearError();
}
}
Forward the user to the information page, with the query string data (#)
<%@ 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">
<div>
<asp:ListBox ID="lstItems"
runat="server"
Height="155px"
Width="165px"></asp:ListBox><br />
<br />
<asp:CheckBox ID="chkDetails"
runat="server"
Text="Show full details" /><br />
<br />
<asp:Button ID="cmdGo"
runat="server"
OnClick="cmdGo_Click"
Text="View Information"
Width="165px" /><br />
<br />
<asp:Label ID="lblError" runat="server" EnableViewState="False"></asp:Label>
</div>
</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">
<div>
<asp:Label ID="lblInfo" runat="server" EnableViewState="False" ></asp:Label>
</div>
</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 += "<br />Show Full Record: ";
lblInfo.Text += Request.QueryString["Mode"];
}
}
Server.Execute
<%@ 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:<br/><br/>" & sw.ToString())
End Sub
</script>
</head>
<body>
<% Execute %>
</body>
</html>
Server.GetLastError()
<%@ 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 & "<br/><br/>")
Server.ClearError()
End Sub
</script>
</head>
<body>
<form runat="server">
<h4><font face="verdana">Cause an Error to Occur...</font></h4>
<asp:button text="CauseError" OnClick="CauseError" runat="server"/>
</form>
</body>
</html>
Server.HtmlDecode
<%@ 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>
Server.HtmlEncode
<%@ 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>
Server.MachineName
<%@ 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 & ".<br>")
End Sub
</script>
</head>
<body>
<% GetMachineName %>
</body>
</html>
Server.MapPath
<%@ 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>
Server.ScriptTimeout
<%@ 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 & ".<br>")
End Sub
</script>
</head>
<body>
<% GetScriptTimeout %>
</body>
</html>
Server.Transfer
<%@ 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>
Server.UrlDecode
<%@ 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>
Server.UrlEncode
<%@ 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">
<h3>Name:</h3>
<input type="text" id="name" runat="server">
<input type="submit" runat="server">
</form>
</body>
</html>
Server.UrlPathEncode
<%@ 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>
text generated by Execute can be embedded in the main response or cached in a writer object
<%@ 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>
<div id="pageContent">
<form id="form1" runat="server">
<asp:Label runat="server" ID="Label1"></asp:Label>
</form>
</div>
</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("<b>Response generated before Execute is called</b><hr>");
StringWriter writer = new StringWriter();
Server.Execute("child.aspx", writer);
builder.Append(writer.ToString());
builder.Append("<hr><b>Response generated after the call to Execute.</b>");
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">
<div>
</div>
</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 <i>child.aspx</i>");
}
}
Use Server.HtmlEncode to encode HTML tags (C#)
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">
<div>
<h1>Properly encoded:</h1>
<div ID="ctrl2" runat="server"/>
<br /><hr /><br />
<h1>Incorrectly encoded:</h1>
<div ID="ctrl1" runat="server"/>
</div>
</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 <b>bold</b> text use the <b> tag.";
ctrl2.InnerHtml = "To <b>bold</b> text use the " + Server.HtmlEncode("<b>") + " tag.";
}
}
Use Server.MapPath() to load the file in the current directory (VB.net)
<%@ 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 & "</b> " & _
reader.Value & "<br>")
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>
Use Server.Transfer to transfer action to another aspx file (C#)
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" >
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button runat="server" ID="cmdPost"
PostBackUrl="NextPage.aspx" Text="Cross-Page Postback" /><br />
<asp:Button runat="server" ID="cmdTransfer" Text="Manual Transfer" OnClick="cmdTransfer_Click" Visible="False" />
</div>
</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" >
<div>
<asp:Label ID="lblInfo" runat="server"></asp:Label></div>
</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 + "<br />";
CrossPage1 prevPage = PreviousPage as CrossPage1;
if (prevPage != null)
{
lblInfo.Text += "You typed in this: " + prevPage.FullName +
"<br />";
}
}
}
}