Controlling Page Execution


The page makes a natural boundary for grouping pieces of the user interface (UI) and application functionality, but often we want to move between pages without user interaction. For example, it is common to have situations in which you want to stop execution of the current page and move the user to another page. This might be the result of a user choice that is detected in code, or it might be a way to retire an application and get users automatically moved to the improved Web site. ASP.NET has several ways of controlling page execution, each appropriate for different circumstances.

Using Response.Redirect

The Response.Redirect method is useful for getting the user to a different page. The HTTP status code returned to the browser changes from the typical 200 to 302. The 302 status code is a signal to the browser that it will receive a new location and should follow it to get to the content. Most browsers follow the redirect directive immediately, and users will hardly notice that an extra request is taking place, although there is a slight delay as the browser issues the second request. In Code Listing 1-7, RedirectToMSN.aspx demonstrates how to use one of the two method signatures of Response.Redirect. The URL passed as a parameter is the MSN home page.

Code Listing 1-7: RedirectToMSN.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
Response.Redirect("http://www.msn.com");
}
</script>
<form runat="server">
You are being redirected to MSN. Click this link to continue:
<a href="www.msn.com">www.msn.com</a>
</form>
end example

Although we have included content with a link to the new destination, most browsers follow the 302 redirect immediately, so the content is never actually seen by the user. The other version of Response.Redirect takes a second Boolean parameter to indicate whether the remainder of the page should be executed. When this second parameter is not given, the result is the same as though false were specified. No matter which override is chosen, the page will end with a ThreadAbortException, which is part of the normal ASP.NET processing for Response.Redirect. The exception occurs as the result of a call to Response.End, which terminates the rest of the page execution. Allowing the rest of the page to execute can be useful when you can detect the need to move the user to another page early but still want code that will execute in a later part of the page life cycle to complete.

Tip

There is a certain amount of overhead related to throwing exceptions in the .NET Framework. Avoid throwing an excessive number of exceptions as part of the regular course of an application.

When using Response.Redirect, the browser must make two requests in order to display the final page to the user. Although the delay might be marginal, the server and the user both pay a price for the round trip.

When a browser receives a 302 Redirect as the result of a GET request, and no form variables are being posted, the browser can simply issue another GET request to the new location. However, when the redirect response comes from a POST request, the browser must decide whether to submit the form variables again to the new location. The HTTP specification states that the browser must first ask the user for permission before posting form data again. Presumably to avoid this potentially confusing question, most browsers follow the redirect without prompting the user and avoid the specification noncompliance by making a GET request and not submitting any form data.

Using Server.Transfer

Response.Redirect sends the user to a new page in the same application or to a different Web site altogether. If you want to send the user to a Web page within the same application, Server.Transfer might be a better choice. It functions in essentially the same way as Response.Redirect in that the current page is aborted, a call to Response.End is made along with the corresponding ThreadAbortException being thrown, and the new page is then executed. However, the extra round trip between client and server is eliminated. With Response.Redirect, you can include a query string in the new location parameter, but the form variables will not be available in the new page. Server.Transfer allows us to preserve the query string and data submitted by the user. The page is executed without the user having any idea that anything other than the original page completed.

Code Listing 1-8 demonstrates transferring page control to another page. In this case, we just give the user a text box and perform the transfer in the OnClick handler for the form’s button.

Code Listing 1-8: TransferSource.aspx

start example
 <script runat="server" language="C#">
protected void DoTransfer(object o, EventArgs e) {
Server.Transfer("TransferDest.aspx", true);
}
</script>
<form runat="server">
Input Something: <asp:textbox runat="server" />
<asp:button type="submit" runat="server" Text="Go"
OnClick="DoTransfer"/>
</form>

The second parameter to the Transfer method indicates whether the form and query string should be available in the destination page. If not specified, the default is to preserve the data. The destination page is shown in Code Listing 1-9. TransferDest.aspx sets the value of a label to the value the user submitted to the source page. Notice that we do this when IsPostBack is false. Although the source page was processing a postback, the destination page is not treated as a postback. The value is carried in view state for subsequent postbacks in which the Transfer handling logic is not involved.

end example

Code Listing 1-9: TransferDest.aspx

start example
 <script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
handlerLabel.Text = HttpContext.Current.Handler.ToString();
executionPath.Text = Request.CurrentExecutionFilePath;
if(!IsPostBack) {
theLabel.Text=Server.HtmlEncode(Request["theFormInput"]);
}
}
</script>
<form runat="server">
Handler: <asp:label runat="server" /><br />
ExecutionPath: <asp:label runat="server" /><br>
<asp:label runat="server" Text="default text" />
<asp:button type="submit" runat="server" Text="PostBack" />
</form>

We also display the name of the handler from the current HttpContext as well as the CurrentExecutionFilePath from the Request intrinsic. When first transferred to the page, the handler name and CurrentExecutionFilePath do not match. This is because the handler listed is still the compiled type of the original request page, ASP.TransferSource_aspx, whereas CurrentExecutionFilePath represents the source page being executed, TransferDest.aspx. When the button on the destination page is clicked, the handler and the file path are again in sync.

Using Server.Execute

ASP.NET provides another option for controlling page execution. The Server.Execute API transfers control to another page, but only temporarily. When the page execution completes, control is returned to the calling page. There is no call to Response.End and no associated ThreadAbortException. Although we’ve pointed out the side effect of the exception, this side effect should not be your primary motivation in choosing a particular API. Rather, you should be aware of what is causing exceptions so that real problems do not go unnoticed.

Code Listing 1-10, ExecutePage.aspx, uses Server.Execute to gather and display the output of another executed page. The page being called, ExecutionFilePath.aspx, is shown in Code Listing 1-11. The first of the two method signatures takes just the path to the target page; the second takes a TextWriter that receives the output from the target page. In ExecutePage.aspx, we create a StringWriter to collect the output and display it after we write the result of our own call to retrieve ExecutionFilePath.

end example

Code Listing 1-10: ExecutePage.aspx

start example
 <%@Import namespace="System.IO" %>
<script runat="server" language="C#">
protected void Page_Load(object o, EventArgs e) {
Response.Write("the current execution file path is:");
Response.Write(Request.CurrentExecutionFilePath + "<br>");

Response.Write("the Server.Execute file path is:");
StringWriter sw = new StringWriter();
Server.Execute("ExecutionFilePath.aspx", sw);
Response.Write(sw.ToString() + "<br>");
}
</script>
end example

The page output demonstrates that control returns to the calling page after the call to Server.Execute and the original page continues its execution.

Code Listing 1-11: ExecutionFilePath.aspx

start example
 <script runat="server" language="C#">
protected void Page_Load(object o, EventArgs e) {
Response.Write(Request.CurrentExecutionFilePath);
}
</script>
end example

Tip

Server.Transfer is essentially the equivalent of Response.End followed by a call to Server.Execute.




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net